Mustafa
Mustafa

Reputation: 59

Why are these datetime objects timezones not equal?

I'm having a problem with datetime objects. Here's my code:

import datetime
import pytz

userInfo = 'Europe/Istanbul'

# Current date, 2020-9-8 15:00
cd = datetime.datetime.now(pytz.timezone(userInfo))

# Example date, 2020-9-8 15:00
ed = datetime.datetime(2020, 9, 8, 15, 0, pytz.timezone(userInfo))

# Print both dates
print('Example', ed, '\n', 'Current', cd, '\n')

if ed == cd:
    print('Equal')
else:
    print('Not worked')

As you can see these dates are equal but when I try to print them it gives me this result:

Example 2020-9-8 15:00:00.000000+01:56
Current 2020-9-8 15:00:00.000000+03:00
Not worked

Timezones are different, why? I'm using same timezone for both objects. How to set timezone as +03:00 (which is Istanbul's timezone) for both objects? Thanks.

Upvotes: 1

Views: 197

Answers (1)

user14243928
user14243928

Reputation:

Your code can't work, because you need to use tzinfo=... :

ed = datetime.datetime(2020, 9, 8, 15, 0, tzinfo=pytz.timezone(userInfo))

But it gives wrong result. I don't know why, but to get what you want, use this form:

ed = pytz.timezone(userInfo).localize(datetime.datetime(2020, 9, 8, 15, 0))

For more info take a look at this post: pytz - Converting UTC and timezone to local time

Upvotes: 3

Related Questions