Search code examples
pythonpython-3.xdatetimepytz

UTC to CST time conversion using pytz python package


I have nested json file which has time zone which is in UTC format I am capturing that and putting it into a column and then trying to convert that to cst by creating a column for CST but it is not converting can anybody help am posting the code below

def extract_json_data(fpath):
    print("Extracting " + fpath)
    f = open(fpath, 'r')
    json_data = json.loads(f.read())
    data = json_data['data']
    dt = datetime.datetime.strptime(json_data['time'], "%Y-%m-%dT%H:%M:%SZ")
    dt_cst = dt.astimezone(timezone('US/Central'))
    _ = [row.update({'time_UTC': dt.strftime("%Y-%m-%dT%H:%M:%SZ"),
                     'time_CST': dt_cst.strftime("%Y-%m-%dT%H:%M:%S CST")}) for row in data]

image showing that time not being converted


Solution

  • Use a format string to parse the timezone, so that the datetime object you work with is timezone-aware:

    from datetime import datetime
    
    # the string actually has timezone information: Z (UTC)
    timestring = "2019-01-01T00:00:00Z"
    
    # wrong:
    dt = datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%SZ")
    # dt is naive:
    # datetime.datetime(2019, 1, 1, 0, 0)
    
    # right:
    dt = datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%S%z")
    # dt now knows it's in UTC:
    # datetime.datetime(2019, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
    

    Now you can change the time of your datetime object to a different timezone:

    import pytz
    tz = pytz.timezone('US/Central')
    dt_cst = dt.astimezone(tz)
    # datetime.datetime(2018, 12, 31, 18, 0, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)
    

    A more convenient solution would be to skip pytz and use dateutil instead:

    import dateutil
    timestring = "2019-01-01T00:00:00Z"
    dt = dateutil.parser.parse(timestring)
    
    # dt
    # datetime.datetime(2019, 1, 1, 0, 0, tzinfo=tzutc())