Python datetime module: using timedelta, timezone, and tzinfo
It's safe to say that working with dates and times is an everyday task for any developer. This is especially true when dealing with time-sensitive data, scheduling, or logging.
Python, with its powerful standard library, provides a simple yet powerful module called datetime
to handle dates and times efficiently.
This article describes the datetime
module, its main classes and functions, and best practices for working with dates and times in Python.
If you use Python in VScode, see this post.
1. Understanding the Python datetime module
The datetime
module in the standard Python library contains the following functions: datetime
,
date
, time
, timedelta
, tzinfo
, and several other classes for date and time manipulation.
Let's start with the most common classes and methods.
1.1. datetime.datetime
This class represents a single point in time with both date and time information. It also provides various methods and attributes for accessing and manipulating date and time values.
So first let's create a datetime
object.
from datetime import datetime
# current date and time
now = datetime.now()
print(now)
# a specific date and time
dt = datetime(2022, 9, 15, 10, 30)
print(dt)
The following attributes can be accessed with this object
from datetime import datetime
now = datetime.now()
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"seconds: {now.second}")
print(f"Milliseconds: {now.microseconds}")
1.2 datetime.date
This class represents a date (year, month, day) and provides methods to work with dates without time information.
First, we'll create a date
object to get the information we want.
from datetime import date
# current date
today = date.today()
print(today)
# a specific date
d = date(2022, 9, 15)
print(d)
1.3. datetime.time
This class represents time (hours, minutes, seconds, milliseconds) and provides methods to work with time values only, without date information.
Create a time
object to get the time information.
from datetime import time
# specific time
t = time(10, 30, 15)
print(t)
1.4. datetime.timedelta
This is a very useful class that represents a period of time and can be used to perform calculations with datetime{:python
objects, such as adding or subtracting days, hours, or minutes.
A timedelta{:python
object can be created as follows..:
from datetime import timedelta
# Declare a duration of 5 days, 3 hours, and 30 minutes in a variable
delta = timedelta(days=5, hours=3, minutes=30)
print(delta)
Let's calculate a specific time period with the datetime{:python
and timedelta{:python
objects.
from datetime import datetime, timedelta
now = datetime.now()
# Calculate after 5 days
future = now + timedelta(days=5)
print(future)
# Calculate 3 hours ago
past = now - timedelta(hours=3)
print(past)
2. Working with time zones and UTC time (UTC TIme)
The datetime
module provides the timezone
class, a subclass of tzinfo
, for working with time zones and UTC (Coordinated Universal Time) offsets.
It also provides the timezone
class, which is a subclass of tzinfo
.
To create a datetime
object that is timezone aware, you can use the timezone
class and the astimezone()
method.
See the example.
from datetime import datetime, timezone
# current UTC time
utc_now = datetime.now(timezone.utc)
print(utc_now)
# convert to another time zone
from pytz import timezone
tz = timezone("Asia/Seoul")
local_now = utc_now.astimezone(tz)
print(local_now)
In the example above, we used the pytz
library, an external package, to handle the given time zone.
The pytz
library is widely used to handle time zone conversions in Python, as it provides an extensive and up-to-date database of time zones.
3. Date and time formatting and parsing
The datetime
module provides two useful methods for formatting and parsing dates and times as strings.
datetime.strptime(date_string, format)
: This method takes two arguments, date_string, a string representation of the date and time, and format, a format string that specifies the structure of the date and time in the input string, to extract time information from a string.datetime.strftime(format)
: This method takes one argument, format, a format string that specifies the desired structure of the output string. This method is called on a datetime object and returns a string representation of the date/time according to the specified format.
from datetime import datetime
# Read time information from a string with the strptime() method
date_string = "15-04-2023 16:30:00"
format_string = "%d-%m-%Y %H:%M:%S"
date_obj = datetime.strptime(date_string, format_string)
print(date_obj) # Output: 2023-04-15 16:30:00
# Convert time information to a string with the strftime() method
new_format_string = "%A, %B %d, %Y at %I:%M %p"
formatted_date = date_obj.strftime(new_format_string)
print(formatted_date) # Output: Saturday, April 15, 2023 at 04:30 PM
4. Best practices for working with dates and times in Python
So far, we've covered the basics of working with dates and times with the Python datetime
module.
Here are some best practices to keep in mind when using this module.
- Timezone awareness: Timezone awareness is an important issue when using the
datetime
object. When working with dates and times in different time zones, always use thedatetime
object to avoid issues like daylight saving time or local time differences. - We recommend using the
pytz
library for time zone conversion. Thepytz
library provides an extensive and up-to-date database of time zones. It is widely used to handle time zone conversions in Python. - To convert a datetime object to a string or to parse information from a string, use the
strftime()
andstrptime( )
methods. These methods provide a consistent and flexible way to handle date and time strings in Python.
5. Conclusion
In this article, we covered the basics of Python's datetime
module, including the main classes and functions for working with dates and times.
We also discussed best practices for handling time zones, formatting strings, and parsing dates and times.
Now, for more specifics, I'd recommend reading the official Python documentation for datetime (opens in a new tab). When it makes sense, the official documentation is always the best guide.
For solutions to specific cases, see the calculate, compare date/time, convert date/time, print date/time post.
Working with dates and times is something you'll encounter often, so take the time to understand it. Once you get the hang of it, you'll be well equipped to perform a variety of date and time manipulation tasks in the future.
