python-course.eu

37. Python Date and Time

By Bernd Klein. Last modified: 03 Feb 2025.

Introduction

Python provides rich functionalities for dealing with date and time data. The standard libraries contains the modules

These modules supply classes for manipulating dates and times in both simple and complex ways.

Especially, the datetime class will be very important for the timeseries of Pandas.

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See our Python training courses

See our Machine Learning with Python training courses

Python Standard Modules for Time Data

Python, Date and Time

The most important modules of Python dealing with time are the modules time, calendar and datetime.

The datetime module provides various classes, methods and functions to deal with dates, times, and time intervals.

The datetime module provides the following classes:

Let's start with a date object.

The Date Class

from datetime import date

x = date(1993, 12, 14)
print(x)

OUTPUT:

1993-12-14

We can instantiate dates in the range from January 1, 1 to December 31, 9999. This can be inquired from the attributes min and max:

from datetime import date

print(date.min)
print(date.max)

OUTPUT:

0001-01-01
9999-12-31

We can apply various methods to the date instance above. The method toordinal returns the proleptic Gregorian ordinal. The proleptic Gregorian calendar is produced by extending the Gregorian calendar backward to dates preceding its official introduction in 1582. January 1 of year 1 is day 1.

x.toordinal()

OUTPUT:

727911

It is possible to calculate a date from a ordinal by using the class method "fromordinal":

date.fromordinal(727911)

OUTPUT:

datetime.date(1993, 12, 14)

If you want to know the weekday of a certain date, you can calculate it by using the method weekday:

x.weekday()

OUTPUT:

1
date.today()

OUTPUT:

datetime.date(2017, 4, 12)

We can access the day, month and year with attributes:

print(x.day)
print(x.month)
print(x.year)

OUTPUT:

14
12
1993

The time Class

The time class is similarly organized than the date class.

from datetime import time

t = time(15, 6, 23