9.1 Working with Date and Time
Programmers often need to work with dates and times in their programs. So it's no surprise that there are two standard libraries in Python for these cases:
datetime
and time
.
The datetime
library is a part of the standard Python library and provides classes for working with dates and times. It allows you to create, manipulate, and format dates and times, as well as perform arithmetic operations with them.
Main classes of the datetime
library
The datetime.date
class
This class represents a date (year, month, day) without time. It's useful for working with calendar dates.
Example usage:
import datetime
# Creating a date object
d = datetime.date(2023, 5, 24)
print(d) # Output: 2023-05-24
# Getting the current date
today = datetime.date.today()
print(today)
# Accessing year, month, and day attributes
print(d.year) # Output: 2023
print(d.month) # Output: 5
print(d.day) # Output: 24
The datetime.time
class
This class represents a time (hours, minutes, seconds, microseconds) without a date. It's useful for working with times of the day.
Example usage:
import datetime
# Creating a time object
t = datetime.time(14, 30, 45)
print(t) # Output: 14:30:45
# Accessing hour, minute, and second attributes
print(t.hour) # Output: 14
print(t.minute) # Output: 30
print(t.second) # Output: 45
The datetime.datetime
class
This class combines a date and time (year, month, day, hours, minutes, seconds, microseconds). It's useful for working with specific moments in time.
Example usage:
import datetime
# Creating a datetime object
dt = datetime.datetime(2023, 5, 24, 14, 30, 45)
print(dt) # Output: 2023-05-24 14:30:45
# Getting the current date and time
now = datetime.datetime.now()
print(now)
# Accessing date and time attributes
print(dt.year) # Output: 2023
print(dt.month) # Output: 5
print(dt.day) # Output: 24
print(dt.hour) # Output: 14
print(dt.minute) # Output: 30
print(dt.second) # Output: 45
The datetime.timedelta
class
This class represents the difference between two points in time, expressed in days, seconds, and microseconds. It's useful for performing arithmetic operations with dates and times.
Example usage:
import datetime
# Creating a timedelta object
delta = datetime.timedelta(days=10, hours=5, minutes=30)
print(delta) # Output: 10 days, 5:30:00
# Adding timedelta to a date
dt = datetime.datetime(2023, 5, 24, 14, 30)
new_dt = dt + delta
print(new_dt) # Output: 2023-06-03 20:00:00
# Subtracting timedelta from a date
earlier_dt = dt - delta
print(earlier_dt) # Output: 2023-05-14 09:00:00
4.2 Formatting and Parsing Dates and Times
We often need not just to work with a date, but to convert it to a string in a specific format. The reverse process, when we convert a string to an object, is usually called parsing. Python also has its own classes and methods for these operations:
The strftime()
method
The strftime()
method is used to format datetime
objects into strings according to a specified format.
Example usage:
import datetime
dt = datetime.datetime(2023, 5, 24, 14, 30, 45)
# Formatting date and time
formatted_dt = dt.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_dt) # Output: 2023-05-24 14:30:45
# Formatting only the date
formatted_date = dt.strftime("%d-%m-%Y")
print(formatted_date) # Output: 24-05-2023
# Formatting only the time
formatted_time = dt.strftime("%H:%M:%S")
print(formatted_time) # Output: 14:30:45
The strptime()
method
The strptime()
method is used to parse strings into datetime
objects according to a specified format.
Example usage:
import datetime
# Parsing a string into a datetime object
date_str = "24-05-2023 14:30:45"
dt = datetime.datetime.strptime(date_str, "%d-%m-%Y %H:%M:%S")
print(dt) # Output: 2023-05-24 14:30:45
# Parsing a string into a date object
date_str = "24-05-2023"
d = datetime.datetime.strptime(date_str, "%d-%m-%Y").date()
print(d) # Output: 2023-05-24
# Parsing a string into a time object
time_str = "14:30:45"
t = datetime.datetime.strptime(time_str, "%H:%M:%S").time()
print(t) # Output: 14:30:45
4.3 Working with Time Zones
As experience shows, people from all over the world use our services, and, unfortunately, they live in different countries and have different time zones (timezone
). So, as a programmer, you need to be able to work with them too.
And of course, Python has a class for this case too:
The timezone
class
The timezone
class from the datetime
module allows you to work with time zones.
import datetime
# Creating a datetime object with UTC timezone
utc_dt = datetime.datetime(2023, 5, 24, 14, 30, 45, tzinfo=datetime.timezone.utc)
print(utc_dt) # Output: 2023-05-24 14:30:45+00:00
# Converting to another timezone
tokyo_tz = datetime.timezone(datetime.timedelta(hours=9))
tokyo_dt = utc_dt.astimezone(tokyo_tz)
print(tokyo_dt) # Output: 2023-05-24 23:30:45+09:00
We've touched on the datetime
library very briefly, just scratching the surface. We'll come back to it in the future and learn to use it for more specific tasks. For now, I just wanted to introduce you to it and broaden your view of the set of standard libraries.
About any library, you should first know that it exists and have an idea of what can be done with it. You can always find a list of functions, their parameters, and all their possibilities in the official documentation.
GO TO FULL VERSION