Home > Mobile >  Formatting a timestamp to date giving wrong result
Formatting a timestamp to date giving wrong result

Time:09-24

I'm trying to format a timestamp 1584474718199 to date but it gives me wrong date. This is what I'm getting 2020-03-18 at this moment whereas the correct date shhould be 2020-03-17. How can I achive that?

My current approach:

from datetime import datetime
timestamp = 1584474718199/1000
dt_object = datetime.fromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d}")

CodePudding user response:

On my computer (located in PST) your code returns:

2020-03-17

Printing the hour minute and second:

timestamp = datetime.fromtimestamp(timestamp)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

Returns:

2020-03-17 12:51:58

It's possible that your local timezone is causing problems, in which case you could try localizing it to UTC:

from datetime import datetime
import pytz
dt_object = datetime.utcfromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d %H:%M:%S}")

Which returns:

2020-03-17 19:51:58

You might want to check your local UTC offset as well:

utc_offset = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
utc_offset_hours = utc_offset.seconds/(60*60)   utc_offset.days*24
print(f"{utc_offset_hours} hours")
  • Related