Nearby lessons

133 of 159

Python - Dates and Time

📌 What You Will Learn
  • Understand the datetime module
  • Use the date, time, and datetime classes
  • Get the current date and time with now()
  • Format dates using strftime()
  • Convert timestamps to readable dates with fromtimestamp()

What is the datetime Module?

The datetime module provides classes to work with dates and times in Python.

It is a standard module, so it is installed with Python and can be used by importing it.

🐍Code Cell
1import datetime
Output
No output captured.

Classes in the datetime Module

The datetime module provides three main classes for working with dates and times.

Class What It Stores Example
date Year, month, and day 2024-08-15
time Hour, minute, second, microsecond 14:30:00
datetime Both date and time 2024-08-15 14:30:00

Creating a date Object

We can create a date object by passing the year, month, and day to the date() constructor.

🐍Code Cell
1from datetime import date
2 
3d = date(2024, 8, 15)
4 
5print(d)
Output
2024-08-15

Creating a time Object

We can create a time object by passing the hour, minute, and second to the time() constructor.

🐍Code Cell
1from datetime import time
2 
3t = time(14, 30, 45)
4 
5print(t)
Output
14:30:45

Creating a datetime Object

The datetime class combines both the date and the time.

🐍Code Cell
1from datetime import datetime
2 
3dt = datetime(2024, 8, 15, 14, 30, 45)
4 
5print(dt)
Output
2024-08-15 14:30:45

Getting the Current Date and Time

We can get the current local date and time using the now() method of the datetime class.

🐍Code Cell
1from datetime import datetime
2 
3now = datetime.now()
4 
5print(now)
Output
2024-08-15 14:30:45.123456

Getting the Current Date Only

To get the current date without the time, we can use the today() method of the date class, or the date() method on a datetime object.

🐍Code Cell
1from datetime import date, datetime
2 
3d = date.today()
4 
5print(d)
6 
7dt = datetime.now()
8print(dt.date())
Output
2024-08-15
2024-08-15

Accessing Individual Components

Individual parts of a date or time can be accessed as attributes.

🐍Code Cell
1from datetime import datetime
2 
3now = datetime.now()
4 
5print("Year:", now.year)
6print("Month:", now.month)
7print("Day:", now.day)
8print("Hour:", now.hour)
9print("Minute:", now.minute)
10print("Second:", now.second)
Output
Year: 2024
Month: 8
Day: 15
Hour: 14
Minute: 30
Second: 45

Formatting Dates with strftime()

We can convert a datetime object into a formatted string using the strftime() method. Format codes are written with a % prefix.

🐍Code Cell
1from datetime import datetime
2 
3now = datetime.now()
4 
5print(now.strftime("%d/%m/%Y"))
6print(now.strftime("%d-%B-%Y"))
7print(now.strftime("%H:%M:%S"))
Output
15/08/2024
15-August-2024
14:30:45

Common Format Codes

Code Meaning Example
%Y 4-digit year 2024
%y 2-digit year 24
%m Month as a number 08
%B Full month name August
%d Day of the month 15
%H Hour (24-hour clock) 14
%M Minute 30
%S Second 45

Converting a Timestamp with fromtimestamp()

Some functions return time as a timestamp, which is a number of seconds since January 1, 1970 at midnight. We can convert such a timestamp into a readable date using fromtimestamp().

By default, fromtimestamp() converts to the system's local timezone, so the result can vary from machine to machine. Passing timezone.utc makes the output deterministic.

🐍Code Cell
1from datetime import datetime, timezone
2 
3timestamp = 1723714245
4 
5dt = datetime.fromtimestamp(timestamp, timezone.utc)
6 
7print(dt)
Output
2024-08-15 09:30:45+00:00

Explanation

The fromtimestamp() function takes a timestamp (seconds since the epoch) and returns the corresponding datetime object.

Without an explicit timezone, the result depends on the system timezone. In the example above, passing timezone.utc shows the timestamp 1723714245 as 2024-08-15 09:30:45+00:00.

This is especially useful when working with file statistics, where values like the last modified time are stored as timestamps.

Comparing Dates

Date and time objects support comparison using the standard operators.

🐍Code Cell
1from datetime import date
2 
3d1 = date(2024, 8, 15)
4d2 = date(2025, 1, 1)
5 
6print(d1 < d2)
7print(d1 == d2)
Output
True
False
📝 Key Takeaways
  • The datetime module provides the date, time, and datetime classes
  • datetime.now() returns the current local date and time
  • strftime() converts a datetime object into a formatted string using format codes
  • datetime.fromtimestamp() converts a timestamp into a datetime object
  • The date class stores year, month, and day; the time class stores hour, minute, second, and microsecond

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10