Search code examples
pythonpython-3.xtimezonepytz

Creating a function with PYTZ's timezones


I'm trying to make a function called to_timezone that will take a timezone name as a string, and then convert 'starter' to that timezone, using pytz's timezones...I want it to return a a new datetime.

I want it to be whatever timezone that comes in as 'tz'. I don't want to hardcode the 'pytz timezone object' How would I accomplish this?
Here is my code:

import datetime

import pytz

starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29))

def to_timezone(tz):
    tz_utc = pytz.timezone('#pytz timezone object')
    starter = tz_utc.astimezone
    return starter

Solution

  • If tz is a timezone name from the tz database such as "America/New_York" then you could pass it directly to pytz.timezone and use astimezone(), normalize() methods to convert an aware datetime object starter to tz timezone:

    def to_timezone(aware_dt, zonename):
        tz = pytz.timezone(zonename)
        return tz.normalize(aware_dt.astimezone(tz))
    

    Example:

    starter = datetime.datetime(2015, 10, 21, 23, 29, tzinfo=pytz.utc)
    print(to_timezone(starter, "America/Los_Angeles"))
    # -> 2015-10-21 16:29:00-07:00