python - How to convert date string to a datetime object in a specified timezone -
i can convert given date string formatted in yyyy-mm-dd
datetime
object using:
from datetime import datetime dt = datetime.strptime(date_str, '%y-%m-%d')
however, uses current machine's timezone default.
is there way specify specific timezone (such utc, pst, etc) in conversion obtained datetime
object in timezone.
i trying in python 3.4.3.
this not possible using python's standard library.
for full flexibility, install python-dateutil
, pytz
, run:
date_str = '2015-01-01' dt = pytz.timezone('europe/london').localize(dateutil.parser.parse(date_str))
this gives datetime europe/london timezone.
if need parsing of '%y-%m-%d'
strings need pytz
:
from datetime import datetime naive_dt = datetime.strptime(date_str, '%y-%m-%d') dt = pytz.timezone('europe/london').localize(naive_dt)
Comments
Post a Comment