Converting unix timestamp string to readable date

前端 未结 15 2226
别跟我提以往
别跟我提以往 2020-11-22 04:30

I have a string representing a unix timestamp (i.e. \"1284101485\") in Python, and I\'d like to convert it to a readable date. When I use time.strftime, I get a

相关标签:
15条回答
  • 2020-11-22 05:01

    You can use easy_date to make it easy:

    import date_converter
    my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
    
    0 讨论(0)
  • 2020-11-22 05:05
    >>> from datetime import datetime
    >>> datetime.fromtimestamp(1172969203.1)
    datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
    

    Taken from http://seehuhn.de/pages/pdate

    0 讨论(0)
  • 2020-11-22 05:08

    In Python 3.6+:

    import datetime
    
    timestamp = 1579117901
    value = datetime.datetime.fromtimestamp(timestamp)
    print(f"{value:%Y-%m-%d %H:%M:%S}")
    

    Output

    2020-01-15 19:51:41
    

    Explanation

    • Line #1: Import datetime library.
    • Line #2: Unix time which is seconds since 1970-01-01.
    • Line #3: Converts this to a unix time object, check with: type(value)
    • Line #4: Prints in the same format as strp.

    Bonus

    To save the date to a string then print it, use this:

    my_date = f"{value:%Y-%m-%d %H:%M:%S}"
    print(my_date)
    
    0 讨论(0)
  • 2020-11-22 05:08

    i just successfully used:

    >>> type(tstamp)
    pandas.tslib.Timestamp
    >>> newDt = tstamp.date()
    >>> type(newDt)
    datetime.date
    
    0 讨论(0)
  • 2020-11-22 05:09

    Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

    Timestamps can be in two formats:

    1. 13 digits(milliseconds) - To convert milliseconds to date, use:

      import pandas
      result_ms=pandas.to_datetime('1493530261000',unit='ms')
      str(result_ms)
      
      Output: '2017-04-30 05:31:01'
      
    2. 10 digits(seconds) - To convert seconds to date, use:

      import pandas
      result_s=pandas.to_datetime('1493530261',unit='s')
      str(result_s)
      
      Output: '2017-04-30 05:31:01'
      
    0 讨论(0)
  • 2020-11-22 05:10

    Another way that this can be done using gmtime and format function;

    from time import gmtime
    print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
    

    Output: 2018-10-4 11:57:44

    0 讨论(0)
提交回复
热议问题