Home > OS >  Python - How to convert datetime object to timezone given as string in a column?
Python - How to convert datetime object to timezone given as string in a column?

Time:07-11

I have a column of UTC times which I need to convert to 'local' times based on the UTC timezone provided in a second column as a string. How do I assign a timezone using pytz to the time in the column based on string UTC timezone provided? enter image description here

CodePudding user response:

tz = timezone('America/New_York')

pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)

astimezone() will convert it to the timezone of your choice. The utc_time variable is your UTC string and tz is the timezone you want it converted to. There's a list of all the pytz timezones here: timezone list

Also, see this thread, there are more answers here

CodePudding user response:

import pytz

# fmt: Etc/GMT{ ,-}{tm}
def format_tz(s:str):
    icon = ' ' # default to plus sign
    s = s.strip()
    if s[0] == '-':
        icon = '-' # change to minus if is minus
    if s[0] in (' ', '-'):
        s = s[1:] # strip pluses and minuses
    i:int = int(s) # change to integer
    return pytz.timezone(f'Etc/GMT{icon}{i}') # convert to timezone

and for the time(excl. milliseconds)

# fmt: yyyy-mm-dd hh:mm:ss.MMM
def format_time(s:str):
    return time.strptime(s[:-5], '%Y-%m-%d %H:%M:%S')
  • Related