1

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}")
MITHU
  • 113
  • 3
  • 12
  • 41
  • Wrong timezone? – sj95126 Sep 22 '21 at 18:48
  • 1
    The [datetime.fromtimestamp documentation](https://docs.python.org/3/library/datetime.html#datetime.date.fromtimestamp) says: "Return the **local** date corresponding to the POSIX timestamp". So, it seems that your timestamp is being treated as UTC, and that your local timezone is ahead of UTC. – Random Davis Sep 22 '21 at 18:53
  • You can simply set the tz to UTC in the fromtimestamp method, see e.g. https://stackoverflow.com/a/65076703/10197418 – FObersteiner Sep 23 '21 at 05:42

1 Answers1

2

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")