How to convert date string to datetime object in specified timezone
I can convert a given date string, formatted to YYYY-MM-DD
, to an object datetime
using:
from datetime import datetime
dt = datetime.strptime(date_str, '%Y-%m-%d')
However, the default is the machine's current time zone.
Is there a way to specify a specific time zone (like UTC, PST, etc.) in the transformation so that the resulting object is datetime
in that time zone.
I am trying to do this in Python 3.4.3.
source to share
This is not possible using only the Python standard library.
For complete flexibility, install python-dateutil
and pytz
and run:
date_str = '2015-01-01'
dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str))
This gives you the time and time with the Europe / London time zone.
If you only want to parse strings '%Y-%m-%d'
, you only need pytz
:
from datetime import datetime
naive_dt = datetime.strptime(date_str, '%Y-%m-%d')
dt = pytz.timezone('Europe/London').localize(naive_dt)
source to share