1

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.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Mustafa
  • 59
  • 1
  • 9
  • 1
    An argument is missing for datetime.datetime. At the place where the timezone info is it should be the microseconds, after that it's the timezone info. – lpeak Sep 08 '20 at 21:10
  • see [this resource](https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html) to find out why... just use `dateutil` instead to avoid such weird behavior. Or `zoneinfo` once Python 3.9 is out. – FObersteiner Sep 09 '20 at 08:13

1 Answers1

3

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