user2406718
user2406718

Reputation: 263

python convert PST time to UTC isoformat

ex: I have a date string

2018-02-17 16:15:36.519 PST

How do i convert into isoformat in UTC like below

2018-02-18T00:15:36.519Z

I tried this

from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
print parse(d1)
it prints like this.  How do i convert it to UTC with Z at the end.
2018-02-17 16:15:36.519000-08:00

EDIT using python 2.7.

import dateutil
import pytz
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
d2=dateutil.parser.parse(d1)
d2.replace(tzinfo=pytz.utc) - d2.utcoffset()
d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat()
print d3

then formatting with Z as suggested

Upvotes: 5

Views: 9099

Answers (2)

Cupider
Cupider

Reputation: 1

This is a demo code from python2.7, FYI, thanks!

from datetime import datetime

from pytz import utc, timezone


def get_current_pst_time():
    print('------------(1) Current time to PST time----------------')
    local_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    utc_time = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S')
    pst_time = datetime.now(tz=utc).astimezone(timezone('US/Pacific')).strftime('%Y-%m-%d %H:%M:%S')
    is_summary_time = bool(datetime.now(tz=utc).astimezone(timezone('US/Pacific')).dst())
    print('is it a summary time? %s.' % is_summary_time)
    print('local time is %s.' % local_time)
    print('utc time is %s.' % utc_time)
    print('pst time is %s.' % pst_time)


def convert_pst_time_to_utc_time(pst_time_str):
    print('------------(2) PST time to UTC time----------------')
    print('pst time is %s.' % pst_time_str)
    temp_time = datetime.strptime(pst_time_str, '%Y-%m-%d %H:%M:%S')
    pacific_timezone = timezone('US/Pacific')
    pst_time = pacific_timezone.localize(temp_time, is_dst=None)
    assert pst_time.tzinfo is not None
    assert pst_time.tzinfo.utcoffset(pst_time) is not None
    is_summary_time = bool(pst_time.dst())
    print('is it a summary time? %s.' % is_summary_time)
    utc_time = pst_time.astimezone(timezone('utc'))
    print('utc time is %s.' % utc_time.strftime('%Y-%m-%d %H:%M:%S'))


def convert_utc_time_to_pst_time(utc_time_str):
    print('------------(3) UTC time to PST time----------------')
    print('utc time is %s.' % utc_time_str)
    temp_time = datetime.strptime(utc_time_str, '%Y-%m-%d %H:%M:%S')
    utc_timezone = timezone('utc')
    utc_time = utc_timezone.localize(temp_time, is_dst=None)
    assert utc_time.tzinfo is not None
    assert utc_time.tzinfo.utcoffset(utc_time) is not None
    pst_time = utc_time.astimezone(timezone('US/Pacific'))
    is_summary_time = bool(pst_time.dst())
    print('is it a summary time? %s.' % is_summary_time)
    print('pst time is %s.' % pst_time.strftime('%Y-%m-%d %H:%M:%S'))


if __name__ == '__main__':
    get_current_pst_time()
    convert_pst_time_to_utc_time('2019-12-03 02:00:00')
    convert_pst_time_to_utc_time('2020-07-03 02:00:00')

    convert_utc_time_to_pst_time('2019-12-03 10:00:00')
    convert_utc_time_to_pst_time('2020-07-03 09:00:00')

Upvotes: 0

jfs
jfs

Reputation: 414079

To parse a time string with a timezone abbreviation (PST) into a timezone-aware datetime object:

import dateparser  # pip install dateparser

pst_dt = dateparser.parse('2018-02-17 16:15:36.519 PST')
# -> datetime.datetime(2018, 2, 17, 16, 15, 36, 519000, tzinfo=<StaticTzInfo 'PST'>)

To convert the time to UTC timezone:

import datetime as DT

utc_dt = pst_dt.astimezone(DT.timezone.utc)
# -> datetime.datetime(2018, 2, 18, 0, 15, 36, 519000, tzinfo=datetime.timezone.utc)

To print it in the desired format:

print(utc_dt.isoformat())  # -> 2018-02-18T00:15:36.519000+00:00
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))  # -> 2018-02-18T00:15:36.519000Z

On Python 2.7 there is no DT.timezone.utc:

utc_naive = psd_dt.replace(tzinfo=None) - psd_dt.utcoffset()
print utc_naive.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# -> 2018-02-18T00:15:36.519000Z

Note: in the general case the timezone abbreviation (such as PST) may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?

In your specific case, the time string corresponds to unique UTC time:

>>> from collections import defaultdict
>>> import datetime as DT
>>> import pytz
>>> naive_dt, tzabbr = DT.datetime(2018, 2, 17, 16, 15, 36, 519000), 'PST'
>>> utc_times = defaultdict(list)
>>> for zone in pytz.all_timezones:
...     dt = pytz.timezone(zone).localize(naive_dt, is_dst=None)
...     if dt.tzname() == tzabbr: # same timezone abbreviation
...         utc_times[dt.astimezone(pytz.utc)].append(zone)
>>> for utc_dt, timezones in utc_times.items():
...     print(f'{utc_dt:%c %Z}', *timezones, sep='\n\t')
Sun Feb 18 00:15:36 2018 UTC
        America/Dawson
        America/Ensenada
        America/Los_Angeles
        America/Santa_Isabel
        America/Tijuana
        America/Vancouver
        America/Whitehorse
        Canada/Pacific
        Canada/Yukon
        Mexico/BajaNorte
        PST8PDT
        US/Pacific
        US/Pacific-New

See linux convert time(for different timezones) to UTC

Upvotes: 9

Related Questions