Python convert pst to utc

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=)

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

Install pytz¶

I am using pytz, which is a time zone definitions package. You can install it using Easy Install. On Ubuntu, do this:

sudo easy_install --upgrade pytz

Add time zone information to a naive datetime object¶

from datetime import datetime
from pytz import timezone

date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC'))
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")

Results:

2009-05-05 22:28:15 UTC+0000

Add non-UTC time zone information to a naive datetime object¶

(Added 2014-05-28)

NOTE: datetime.replace() does not handle daylight savings time correctly. The correct way is to use timezone.localize() instead. Using datetime.replace() is OK when working with UTC as shown above because it does not have daylight savings time transitions to deal with. See the pytz documentation.

from datetime import datetime
from pytz import timezone

date_str = "2014-05-28 22:28:15"
datetime_obj_naive = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

# Wrong way!
datetime_obj_pacific = datetime_obj_naive.replace(tzinfo=timezone('US/Pacific'))
print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")

# Right way!
datetime_obj_pacific = timezone('US/Pacific').localize(datetime_obj_naive)
print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")

Results:

2014-05-28 22:28:15 PST-0800
2014-05-28 22:28:15 PDT-0700

Convert time zones¶

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(fmt)

# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)

# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)

Results:

2009-05-06 03:09:49 UTC+0000
2009-05-05 20:09:49 PDT-0700
2009-05-06 05:09:49 CEST+0200

List time zones¶

There are 559 time zones included in pytz. Here's how to print the US time zones:

from pytz import all_timezones

print len(all_timezones)
for zone in all_timezones:
    if 'US' in zone:
        print zone

Results:

US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Pacific-New
US/Samoa

See also:¶

  • http://docs.python.org/library/datetime.html - Python datetime module documentation
  • http://uswaretech.com/blog/2009/02/understanding-datetime-tzinfo-timedelta-timezone-conversions-python/ - More info on tzinfo and datetime objects.

How do you convert to UTC in Python?

How to convert local datetime to UTC in Python.
local_time = pytz. timezone("America/New_York").
naive_datetime = datetime. datetime. ... .
local_datetime = local_time. localize(naive_datetime, is_dst=None) ... .
utc_datetime = local_datetime. astimezone(pytz. ... .
print(utc_datetime) Output..

How do you convert datetime to UTC?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

How do I change timezone in python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.

What is Tzinfo in Python?

tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.