How do I get the first datetime of the day?
1 answer
Use the method localize()
to add a timezone:
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone('America/Sao_Paulo')
naive = datetime(2014, 10, 19)
aware = tz.localize(naive, is_dst=None)
If you run the code; it generates NonExistentTimeError
. How to deal with this error depends on the application, for example, to get some valid local time around midnight:
aware = tz.normalize(tz.localize(naive, is_dst=False))
Or you can increase the time by a minute until you get the actual local time (Sao Paulo):
from datetime import datetime, timedelta
import pytz # $ pip install pytz
tz = pytz.timezone('America/Sao_Paulo')
d = naive = datetime(2014, 10, 19)
while True:
try:
aware = tz.localize(d, is_dst=None)
except pytz.AmbiguousTimeError:
aware = tz.localize(d, is_dst=False)
assert tz.localize(d, is_dst=False) > tz.localize(d, is_dst=True)
break
except pytz.NonExistentTimeError:
d += timedelta(minutes=1) # try future time
continue
else:
break
Result:
>>> aware
datetime.datetime(2014, 10, 19, 1, 0, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRST-1 day, 22:00:00 DST>
>>> aware.strftime('%Y-%m-%d %H:%M:%S %Z%z')
'2014-10-19 01:00:00 BRST-0200'
Note: the first valid time 01:00
on that day. And the time zone is two hours below UTC (local = utc - 2).
+3
source to share