4.7. datetime#

The datetime module is very handy when working with dates and times.

4.7.1. Date#

We can import date from the datetime module.

from datetime import date

This will allow us to create date objects, which we can treat as a new type of Python variable specifically used for handling dates. We create a date object as follows:

date(year, month, day)
from datetime import date

d = date(2025, 1, 31) # 31st of January 2024
print(d)
2025-01-31

We can extract the year, month and day of a date using .year, .month and .day respectively.

from datetime import date

d = date(2025, 1, 31) # 31st of January 2024
print(d.year)
print(d.month)
print(d.day)
2025
1
31

We can also extract out the day of the week. .weekday() will return an integer where Monday is 0 and Sunday is 6. We can then use this to index a list.

from datetime import date

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
d = date(2025, 1, 31) # 31st of January 2024

print(days[d.weekday()])
Friday

4.7.2. Time#

We can import time from the datetime module.

from datetime import time

This will allow us to create time objects using the following (in 24 hour time):

time(hour, minute, second)

We can also access the hour, minute and second using .hour, .minute and .second.

from datetime import time

t = time(17, 35, 20)
print(t)
print(t.hour)
print(t.minute)
print(t.second)
17:35:20
17
35
20

4.7.3. datetime#

datetime objects combine the functionality of date and time objects. To import this we use

from datetime import datetime

We can create a datetime object using

datetime(year, month, day, hour, minute, second)
from datetime import datetime

dt = datetime(2025, 1, 31, 17, 35, 20)
print(dt)
2025-01-31 17:35:20

Just like with the date and time objects we can extract out the year, month, day, day of the week, hour minute and second.

from datetime import datetime

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

dt = datetime(2025, 1, 31, 17, 35, 20)
print(dt.year)
print(dt.month)
print(dt.day)
print(days[dt.weekday()])
print(dt.hour)
print(dt.minute)
print(dt.second)
2025
1
31
Friday
17
35
20

We can also obtain the current date and time.

from datetime import datetime
print(datetime.now())
2025-02-17 05:51:46.819324

4.7.4. timedelta#

timedelta objects allow us to measure a change in time.

from datetime import timedelta

Often the Greek symbol delta (\(\Delta\)) is used to indicate a change in a quantity, which in our case will be time. When creating a timedelta object you can specify days, second, minutes, hours or weeks, all of which are optional and by default each is 0. This allows us to increment times.

timedelta(days=days, seconds=seconds, minutes=minutes, hours=hours, weeks=weeks)

For example, we can add ‘5 days and 2 hours’ to the 31st of January 2025 at 17:35:20, which gets us to the 5th of February 2025 at 19:35:20.

from datetime import datetime, timedelta

dt = datetime(2025, 1, 31, 17, 35, 20)
delta = timedelta(days=5, hours=2)

print(dt + delta)
2025-02-05 19:35:20

timedelta objects only allow you to extract days .days and seconds .seconds (of the time component). This means that to obtain hours, minutes and seconds you need to perform a calculation.

To obtain hours, we need to take the seconds, divide by 60 to get minutes and then divide by 60 to get the number of hours. This is equivalent to dividing by 3600. We then need to round down. We can round down by performing integer division which uses a //. This performs a division and truncates the result to an integer.

To obtain minutes, we convert the seconds to minutes by dividing by 60. But then we only want remainder of minutes that didn’t contribute to a full hour. Since an hour is 60 minutes, we then perform % 60.

from datetime import datetime, timedelta

sunrise = datetime(2025, 1, 30, 6, 15, 30)
sunset = datetime(2025, 1, 31, 20, 2, 00)
delta = sunset - sunrise
hours = delta.seconds//3600
minutes = (delta.seconds // 60) % 60

print('Time difference: {}'.format(delta))
print('Days: {}'.format(delta.days))
print('Hours: {}'.format(hours))
print('Minutes: {}'.format(minutes))
Time difference: 1 day, 13:46:30
Days: 1
Hours: 13
Minutes: 46
Question 1

We have previously seen how hours and minutes can be extracted from a timedelta object. Which of the following would allow you to extract seconds?

  1. seconds = delta.seconds
    
  2. seconds = delta.seconds % 60
    
  3. seconds = delta.seconds % 3600
    
  4. seconds = (delta.seconds//3600) % 60
    
  5. seconds = (delta.seconds//60) % 3600
    
Solution

To obtain seconds, we want the remainder of seconds that didn’t contribute to a full minute. Since a minute is 60 seconds, we perform % 60 to obtain seconds.

For example

from datetime import datetime, timedelta

sunrise = datetime(2025, 1, 30, 6, 15, 30)
sunset = datetime(2025, 1, 31, 20, 2, 00)
delta = sunset - sunrise
seconds = delta.seconds % 60

print('Time difference: {}'.format(delta))
print('Seconds: {}'.format(seconds))
Time difference: 1 day, 13:46:30
Seconds: 30
Question 2

What do you think the output of the following code will be?

from datetime import time

t = time(8, 10, 5)
print('{}:{}'.format(t.hour, t.minute))
  1. 8:10:5
    
  2. 8:10
    
  3. 10:5
    
  4. 8
    10
    5
    
  5. 20:10
    
Solution

Solution is locked

Question 3

Write a program that would tell you which day of the week the 1st of January 2050 would be.

Solution

Solution is locked

Question 4

You have just put your clothes in the washing machine. It will take 3 hours and 15 minutes for the washing to finish. Write a program that will tell you when your washing will finish.

Solution

Solution is locked

Code challenge: What Day Is Your Birthday?

Write a program that lets the user check which day of the week their birthday will fall on for a given year. The user should enter their birthday in DD/MM (day/month) format and then specify a year. The program should then tell the user which day of the week their birthday will fall on for that year.

Example 1

Enter your birthday in the form DD/MM: 24/11
Enter a year: 2025
In 2025 your birthday will be on a Monday

Example 2

Enter your birthday in the form DD/MM: 09/06
Enter a year: 2028
In 2028 your birthday will be on a Friday

You can assume you will be given a valid day, i.e. you won’t be asked about the 29th of February on a non-leap year.

Solution

Solution is locked

Code challenge: End Of Year Countdown

Write a program that tells you how long you have to wait until next year. The output of your program should be formatted as follows with the X’s replaced with appropriate numbers. The number of digits will vary depending on how long it is until the new year.

XXX days XX hours XX minutes XX seconds until XXXX!

For this exercise you must:

  • get the current time using now() from datetime.datetime

  • Extension: Update the text so that if any of the values are 1 the following word becomes singular. E.g. instead of 1 hours it would say 1 hour. *

Solution

Solution is locked