Times and dates
The datetime object
The Python datetime module includes the function now, which returns a datetime object containing the current date and time. The default printout of a datetime object looks like this:
from datetime import datetime
my_time = datetime.now()
print(my_time)
2021-10-19 08:46:49.311393
You can also define the object yourself:
from datetime import datetime
my_time = datetime(1952, 12, 24)
print(my_time)
1952-12-24 00:00:00
By default, the time is set to midnight, as we did not give a time of day in the example above.
Different elements of the datetime object can be accessed in the following manner:
from datetime import datetime
my_time = datetime(1952, 12, 24)
print("Day:", my_time.day)
print("Month:", my_time.month)
print("Year:", my_time.year)
Day: 24 Month: 12 Year: 1952
A time of day can also be specified. The precision can vary, as you can see below:
from datetime import datetime
pv1 = datetime(2021, 6, 30, 13) # 30.6.2021 at 1PM
pv2 = datetime(2021, 6, 30, 18, 45) # 30.6.2021 at 6.45PM
Compare times and calculate differences between them
The familiar comparison operators work also on datetime objects:
from datetime import datetime
time_now = datetime.now()
midsummer = datetime(2021, 6, 26)
if time_now < midsummer:
print("It is not yet Midsummer")
elif time_now == midsummer:
print("Happy Midsummer!")
elif time_now > midsummer:
print("It is past Midsummer")
It is past Midsummer
The difference between two datetime objects can be calculated simply with the subtraction operator:
from datetime import datetime
time_now = datetime.now()
midsummer = datetime(2021, 6, 26)
difference = midsummer - time_now
print("Midsummer is", difference.days, "days away")
Midsummer is -116 days away
NB: the result of the datetime subtraction is a timedelta object. It is less versatile than the datetime
object. For instance, you can access the number of days in a timedelta
object, but not the number of years, as the length of a year varies. A timedelta
object contains the attributes days
, seconds
and microseconds
. Other measures can be passed as arguments, but they will be converted internally.
Similarly, addition is available between datetime
and timedelta
objects. The result will be the datetime
produced when the specified number of days (or weeks, seconds, etc) is added to a datetime
object:
from datetime import datetime, timedelta
midsummer = datetime(2021, 6, 26)
one_week = timedelta(days=7)
week_from_date = midsummer + one_week
print("A week after Midsummer it will be", week_from_date)
long_time = timedelta(weeks=32, days=15)
print("32 weeks and 15 days after Midsummer it will be", midsummer + long_time)
A week after Midsummer it will be 2021-07-03 00:00:00 32 weeks and 15 days after Midsummer it will be 2022-02-20 00:00:00
Let's see how a higher precision works:
time_now = datetime.now()
midnight = datetime(2021, 6, 30)
difference = midnight - time_now
print(f"Midnight is still {difference.seconds} seconds away")
Midnight is still 8188 seconds away
Formatting times and dates
The datetime
module contains a handy method strftime for formatting the string representation of a datetime object. For example, the following code will print the current date in the format dd.mm.yyyy
, and then the date and time in a different format:
from datetime import datetime
my_time = datetime.now()
print(my_time.strftime("%d.%m.%Y"))
print(my_time.strftime("%d/%m/%Y %H:%M"))
19.10.2021 19/10/2021 09:31
Time formatting uses specific characters to signify specific formats. The following is a list of a few of them (please see the Python documentation for a complete list):
Notation | Significance |
---|---|
%d | day (01–31) |
%m | month (01–12) |
%Y | year in 4 digit format |
%H | hours in 24 hour format |
%M | minutes (00–59) |
%S | seconds (00–59) |
You can also specify the delimiter between the different elements, as seen in the examples above.
Datetime formatting works in the reverse direction as well, in case you need to parse a datetime object from a string given by the user. The method strptime will do just that:
from datetime import datetime
birthday = input("Please type in your birthday in the format dd.mm.yyyy: ")
my_time = datetime.strptime(birthday, "%d.%m.%Y")
if my_time < datetime(2000, 1, 1):
print("You were born in the previous millennium")
else:
print("You were born during this millennium")
Please type in your birthday in the format dd.mm.yyyy: 5.11.1986 You were born in the previous millennium
You can check your current points from the blue blob in the bottom-right corner of the page.