Converting unix timestamp string to readable date

前端 未结 15 2212
别跟我提以往
别跟我提以往 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:11

    Use datetime module:

    from datetime import datetime
    ts = int("1284101485")
    
    # if you encounter a "year is out of range" error the timestamp
    # may be in milliseconds, try `ts /= 1000` in that case
    print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
    
    0 讨论(0)
  • 2020-11-22 05:14

    The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

    datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
    

    Where posix_time is the Posix epoch time you want to convert

    0 讨论(0)
  • 2020-11-22 05:14
    import datetime
    temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
    print temp
    
    0 讨论(0)
  • 2020-11-22 05:17

    You can convert the current time like this

    t=datetime.fromtimestamp(time.time())
    t.strftime('%Y-%m-%d')
    '2012-03-07'
    

    To convert a date in string to different formats.

    import datetime,time
    
    def createDateObject(str_date,strFormat="%Y-%m-%d"):    
        timeStamp = time.mktime(time.strptime(str_date,strFormat))
        return datetime.datetime.fromtimestamp(timeStamp)
    
    def FormatDate(objectDate,strFormat="%Y-%m-%d"):
        return objectDate.strftime(strFormat)
    
    Usage
    =====
    o=createDateObject('2013-03-03')
    print FormatDate(o,'%d-%m-%Y')
    
    Output 03-03-2013
    
    0 讨论(0)
  • 2020-11-22 05:18

    For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

    import os, datetime
    
    datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
    

    Output:

    'December 26, 2012'

    0 讨论(0)
  • 2020-11-22 05:20
    timestamp ="124542124"
    value = datetime.datetime.fromtimestamp(timestamp)
    exct_time = value.strftime('%d %B %Y %H:%M:%S')
    

    Get the readable date from timestamp with time also, also you can change the format of the date.

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