JavaScript
x
2
1
datetime.datetime.utcnow()
2
Why does this datetime
not have any timezone info given that it is explicitly a UTC datetime
?
I would expect that this would contain tzinfo
.
Advertisement
Answer
That means it is timezone naive, so you can’t use it with datetime.astimezone
you can give it a timezone like this
JavaScript
1
5
1
import pytz # 3rd party: $ pip install pytz
2
3
u = datetime.utcnow()
4
u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset
5
now you can change timezones
JavaScript
1
2
1
print(u.astimezone(pytz.timezone("America/New_York")))
2
To get the current time in a given timezone, you could pass tzinfo to datetime.now()
directly:
JavaScript
1
6
1
#!/usr/bin/env python
2
from datetime import datetime
3
import pytz # $ pip install pytz
4
5
print(datetime.now(pytz.timezone("America/New_York")))
6
It works for any timezone including those that observe daylight saving time (DST) i.e., it works for timezones that may have different utc offsets at different times (non-fixed utc offset). Don’t use tz.localize(datetime.now())
— it may fail during end-of-DST transition when the local time is ambiguous.