5

I receive 2 different formats of datetime in string format. But While storing in PostgreSql Database it has to be stored in UTC format.

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

Tried using timestamptz in PostgreSql but I guess it doesn't seem to understand AMERICA/NEW_YORK so how can to convert and store in UTC format in DB

-4:00 and AMERICA/NEW_YORK are just example but it can be anything else.

2
  • 1
    Did you try the dateutil.parser? Here is a link: dateutil.readthedocs.io/en/stable/parser.html It should be not to hard to parse the timezone information and reformat it. Edit: it's actually from dateutil.tz import gettz Commented Aug 30, 2017 at 10:45
  • for gettz i need to know the timezone right so should I parse the string and get the timezone from it Commented Aug 30, 2017 at 10:52

1 Answer 1

3

I'd do something like this: First try to parse it altogether, if this fails 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)
Sign up to request clarification or add additional context in comments.

6 Comments

_parsed_tz = tz.gettz(_tz) is giving None for AMERICA/NEW_YORK. Since its none it crashes in catch block
@Sharath are you running this on a windows machine?
I am using Ubuntu 16.04
I tried hard coding it print(tz.gettz('AMERICA/NEW_YORK')) so it gives None
Can you try it with 'America/New_York'? If that works, add .title() to _tz. (see updated answer).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.