3

I can convert a given date string formatted in YYYY-MM-DD to a datetime object using:

from datetime import datetime
dt = datetime.strptime(date_str, '%Y-%m-%d')

However, this uses the current machine's timezone by default.

Is there a way to specify a specific timezone (such as UTC, PST, etc) in the conversion so that the obtained datetime object is in that timezone.

I am trying to do this in Python 3.4.3.

skyork
  • 7,113
  • 18
  • 63
  • 103
  • possible duplicate of [Python Timezone conversion](http://stackoverflow.com/questions/10997577/python-timezone-conversion) – Peter Tillemans Jun 04 '15 at 07:46
  • see http://stackoverflow.com/questions/10997577/python-timezone-conversion – Peter Tillemans Jun 04 '15 at 07:46
  • If you are thing to use timezone except UTC then you should read this http://stackoverflow.com/a/117615 – Tanveer Alam Jun 04 '15 at 07:46
  • Look at this question https://stackoverflow.com/questions/7065164/how-to-make-an-unaware-datetime-timezone-aware-in-python – Matthew Runchey Jun 04 '15 at 07:49
  • Thank you for the pointers. It seems like most solutions utilize `pytz`, but I wonder if there is something built-in in Python 3.4 that may help solving the problem. – skyork Jun 04 '15 at 07:58
  • 1
    @skyork: no. Python 3.4 does not provide a portable access to a timezone database. On Unix, you could set `TZ` envvar and call `time.tzset()` to change your local timezone. Otherwise, you need 3rd party modules such as `pytz`. There is old [PEP 0431 -- Time zone support improvements](https://www.python.org/dev/peps/pep-0431/); it is not clear whether it will be included in Python 3.5. – jfs Jun 04 '15 at 23:33

1 Answers1

3

This is not possible using only Python's standard library.

For full 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 a datetime with Europe/London timezone.

If you only need parsing of '%Y-%m-%d' strings then 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)
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180