Handling Datetimes with Timezones

Intuitive Python — by David Muller (32 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Serializing Python Objects with the pickle Mo dule | TOC | Getting Caught with Sticky Default Arguments 👉

Python’s datetime module allows your programs to manipulate dates and times in high-level ways. You can, for example, use arithmetic to calculate the difference between dates and advance dates forward and backward through time.

This section introduces a particularly thorny part of the datetime library: dealing with timezones. You won’t need to know the ins and outs of the datetime module to follow along with this section, but feel free to consult the Python datetime docs if you are interested.[79]

Using datetime with and without Timezones

Python provides the datetime object to represent specific points in time (for example, October 11th 2020 at 7:42 p.m.). By design, Python allows users to work with two variants of datetime objects: datetimes with timezones, and datetimes without timezones.

Here is an example of datetime object with a timezone:

​ >>> ​from​ ​datetime​ ​import​ datetime, timezone
​ >>> datetime.now(timezone.utc)
​ datetime.datetime(2020, 10, 11, 19, 42, 43, 976988, tzinfo=datet
​ ime.timezone.utc)

Calling datetime.now(timezone.utc) returns a datetime object representing the current time in the UTC timezone. This is a datetime with a timezone. The…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.