Converting unix timestamp string to readable date

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

提交回复
热议问题