Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a UTC `datetime` object in Python?

People also ask

How do I format a datetime UTC in Python?

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime. astimezone() method to convert the datetime to UTC.

How do I create a datetime UTC?

Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.

How do I set UTC in Python?

To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz. utc)'.

Is datetime in UTC Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.


There are fixed-offset timezones in the stdlib since Python 3.2:

from datetime import datetime, timezone

t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=timezone.utc)

Constructor is :

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

Docs link.

Though it is easy to implement utc timezone on earlier versions:

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTCtzinfo(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTCtzinfo()
t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=utc)

I used a lot in pytz and very satisfied from this module.

pytz

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).

Also I would recommend for reading: Understanding DateTime, tzinfo, timedelta & TimeZone Conversions in python