Often, in our projects, we need to work with dates and time. For example, we may want to track the current date and time or see how long our code runs. For these purposes, we can use the datetime module. Let's look closely at what we can do with it.
datetime module classes
The datetime module has several classes that make working with time easy:
datetime.daterepresents standard date;datetime.timerepresents standard time, independent from the date;datetime.timedeltarepresents the difference between two points in time;datetime.tzinforepresents timezones;datetime.datetimerepresents both time and date together.
In this topic, we'll focus on the datetime.datetime class.
datetime.datetime
The datetime.datetime class is a sort of combination of the date and time classes. Similarly to those two, it assumes the current Gregorian calendar and that there are exactly 86,400 seconds in each day.
The constructor of the datetime.datetime objects takes the following parameters:
import datetime
# necessary parameters
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
The year, month and day parameters are required, others are optional. All arguments (except tzinfo) should be integers and just like in real life, their values are restricted:
datetime.MINYEAR(1) ≤year≤datetime.MAXYEAR(9999);1 ≤
month≤ 12;1 ≤
day≤ number of days in this month and year;0 ≤
hour< 24;0 ≤
minute< 60;0 ≤
second< 60;0 ≤
microsecond< 1,000,000;foldin [0, 1].
The tzinfo argument can be an instance of the datetime.tzinfo class, but its default value is None, so we don't need to worry about it here.
To see how this all works, let's create a datetime.datetime object. For example, the date and time of the first human going to space which took place on April 12, 1961, at 6:07 UTC:
import datetime
vostok_1 = datetime.datetime(1961, 4, 12, 6, 7)
print(vostok_1) # 1961-04-12 06:07:00datetime methods
The datetime.datetime class has several very handy methods.
If you need to get the current time and date, there are two methods you can use: datetime.datetime.today() and datetime.datetime.now(tz=None). They are very similar and the only difference between these two methods is that datetime.datetime.now() has a keyword argument tz. If you don't specify it, the two methods work the same. However, in some cases or on some platforms, the datetime.datetime.now() method may be more precise.
This is an example of how they perform:
print(datetime.datetime.now()) # 2019-09-12 17:18:23.620734
print(datetime.datetime.today()) # 2019-09-12 17:18:23.625716
You can also transform a datetime.datetime object to a datetime.time or datetime.date objects using datetime.datetime.time() or datetime.datetime.date() methods respectively:
print(vostok_1.time()) # 06:07:00
print(vostok_1.date()) # 1961-04-12datetime.timedelta
Thetimedelta is a class defined in the datetime module that represents the difference between two dates or times. It allows you to perform various operations on date and time intervals, such as addition, subtraction, and comparisons. A timedelta object represents a duration, not a specific point in time.
The constructor of the datetime.timedelta object takes the following parameters:
import datetime
# necessary parameters
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Here are some examples of using timedelta:
from datetime import datetime, timedelta
# Creating a timedelta object with specific values
delta = timedelta(days=5, hours=3, minutes=30)
# Getting the current date and time
now = datetime.now()
print("Now:", now) # Now: 2023-07-23 18:50:06.392339
# Adding timedelta to the current date and time
future_time = now + delta
print("Future:", future_time) # Future: 2023-07-28 22:20:06.392339
# Subtracting timedelta from the current date and time
past_time = now - delta
print("Past:", past_time) # Past: 2023-07-18 15:20:06.392339
# Comparing two timedelta objects
delta1 = timedelta(days=2)
delta2 = timedelta(weeks=1)
if delta1 < delta2:
print("delta1 is smaller than delta2")
else:
print("delta1 is greater than or equal to delta2")
# delta1 is smaller than delta2
# Representing a duration
task_duration = timedelta(hours=8, minutes=45)
print("The task duration is:", task_duration) # The task duration is: 8:45:00
timedelta is useful when dealing with durations and time differences, while the datetime class is suitable for representing specific points in time. Together, they provide a powerful toolset for working with date and time in Python.Summary
To sum up, in this topic, we've familiarized ourselves with Python datetime module, its datetime.datetime class and some of the methods it has. Those were just a couple of methods available in the datetime.datetime class. There are many more: the ones that deal with timestamps or timezones or the ones that help parse and convert datetime objects. Don't worry, you'll have a chance to work with them in the next topics!