dataviews
dataviews

Reputation: 3100

python datetime formatting confusion

Correct me if I'm wrong, but assume we have the date:

Wed, 27 Jun 2018 11:20:33 -0500

If we use the datetime in python to convert this (datetime.datetime.strptime('Wed, 27 Jun 2018 11:20:33 -0500', '%a, %d %b %Y %H:%M:%S %z')), this generates a time 1 hour greater than UTC, which comes out to 12:20:33. However, in reality shouldn't this be UTC-5 (minus 5 hours). I am taking this date format that is being stored in an XML file. Many of them have -0500 or +0000 at the end of the timestamp. Am I missing something here?

import datetime
dt = datetime.datetime.strptime('Wed, 27 Jun 2018 11:20:33 -0500',
                                 '%a, %d %b %Y %H:%M:%S %z')
print(dt.timestamp())

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

Upvotes: 1

Views: 423

Answers (1)

nosklo
nosklo

Reputation: 222852

It correctly generated the timezone here

>>> import datetime
>>> datetime.datetime.strptime('Wed, 27 Jun 2018 11:20:33 -0500', '%a, %d %b %Y %H:%M:%S %z')
datetime.datetime(2018, 6, 27, 11, 20, 33, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))

datetime.timedelta(-1, 68400) means -5 hours which is correct.

You should add to your question all steps that lead to your "incorrect" result, and what you expect instead.

EDIT: Now that you edited your question - your problem comes from the utilization of .timestamp() and .fromtimestamp() - those methods are timezone naive, so they don't preserve timezone information.

You have to store it yourself if you want:

t = datetime.datetime.strptime('Wed, 27 Jun 2018 11:20:33 -0500', '%a, %d %b %Y %H:%M:%S %z')

stamp = t.timestamp()
stored_zone = t.tzinfo

t2 = datetime.datetime.fromtimestamp(stamp, tz=stored_zone)

This will generate the equivalent datetime object again, with the same timezone, so t == t2

t3 = datetime.datetime.fromtimestamp(stamp, tz=datetime.timezone.utc)

This will generate the same datetime again, but in utc timezone, so it will show up as 16:20 but internally it is the same time, still t == t3!!! Just the timezone is different but both represent the same moment in time.

Timezones are confusing. I recommend reading the docs multiple times and testing all the things. Or just use pytz.

Upvotes: 6

Related Questions