Convert string to DateTime format in UTC in Python, postgresql

I get 2 different date and time formats in string format. But when stored in the PostgreSql database, it must be stored in UTC.

Format 1 : 2017-08-25 01:10:56.910523 -04:00
Format 2 : 2017-08-25 01:10:56.910523 AMERICA/NEW_YORK

I tried using timestamptz in PostgreSql, but it seems that it does not understand AMERICA / NEW_YORK , since it can be converted and saved in UTC to DB

-4: 00 and AMERICA / NEW_YORK are an example, but it could be something else.

+4
source share
1 answer

I would do something like this: First try to parse it altogether, if it fails to parse it separately.

from dateutil import parser, tz
utc_tz = tz.gettz('UTC')

times = ['2017-08-25 01:10:56.910523 -04:00',
         '2017-08-25 01:10:56.910523 AMERICA/NEW_YORK']

for t in times:
    try:
        utc_time = parser.parse(t).astimezone(utc_tz)
    except ValueError as e:
        _date, _time, _tz = t.split(' ')
        _time_wo_tz = parser.parse(' '.join([_date, _time]))
        _parsed_tz = tz.gettz(_tz.title())
        _time_w_tz = _time_wo_tz.replace(tzinfo=_parsed_tz)
        utc_time = _time_w_tz.astimezone(utc_tz)

    print(utc_time)
+2
source

Source: https://habr.com/ru/post/1684739/


All Articles