Converting unix timestamp string to readable date

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

    There are two parts:

    1. Convert the unix timestamp ("seconds since epoch") to the local time
    2. Display the local time in the desired format.

    A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

    #!/usr/bin/env python
    from datetime import datetime
    import tzlocal  # $ pip install tzlocal
    
    unix_timestamp = float("1284101485")
    local_timezone = tzlocal.get_localzone() # get pytz timezone
    local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
    

    To display it, you could use any time format that is supported by your system e.g.:

    print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
    print(local_time.strftime("%B %d %Y"))  # print date in your format
    

    If you do not need a local time, to get a readable UTC time instead:

    utc_time = datetime.utcfromtimestamp(unix_timestamp)
    print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
    

    If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

    local_time = datetime.fromtimestamp(unix_timestamp)
    print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
    

    On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

    #!/usr/bin/env python3
    from datetime import datetime, timezone
    
    utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
    local_time = utc_time.astimezone()
    print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
    

    Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

    #!/usr/bin/env python
    import time
    
    unix_timestamp  = int("1284101485")
    utc_time = time.gmtime(unix_timestamp)
    local_time = time.localtime(unix_timestamp)
    print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
    print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  
    

提交回复
热议问题