Datetime Module

What You'll Learn: In this tutorial, you'll discover how to work with dates in Python using the datetime module. Dates aren't a data type of their own in Python, so we use this module to create and manipulate date objects.

Importing the datetime Module and Displaying the Current Date

You can use the datetime module to get the current date and time.

Example Code:

python
import datetime

x = datetime.datetime.now()
print(x)

Output:

 
2024-11-19 13:04:55.684672

Display Year and Weekday

The datetime module has many methods to return information about the date object.

Example Code:

python
import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

Output:

 
2024
Tuesday

Creating Date Objects

To create a date, use the datetime() class (constructor) of the datetime module. You need to provide the year, month, and day.

Example Code:

python
import datetime

x = datetime.datetime(2020, 5, 17)
print(x)

Using the strftime() Method

The strftime() method formats date objects into readable strings. It takes one parameter, format, to specify the format of the returned string.

Example Code:

python
import datetime

x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))

Output:

 
June

Reference of Format Codes

Here are some common format codes you can use with the strftime() method:

DirectiveDescriptionExampleTry it
%aWeekday, short versionWed 
%AWeekday, full versionWednesday 
%wWeekday as a number 0-6, 0 is Sunday3 
%dDay of month 01-3131 
%bMonth name, short versionDec 
%BMonth name, full versionDecember 
%mMonth as a number 01-1212 
%yYear, short version, without century18 
%YYear, full version2018 
%HHour 00-2317 
%IHour 00-1205 
%pAM/PMPM 
%MMinute 00-5941 
%SSecond 00-5908 
%fMicrosecond 000000-999999548513 
%zUTC offset+0100 
%ZTimezoneCST 
%jDay number of year 001-366365 
%UWeek number of year, Sunday as the first day of week, 00-5352 
%WWeek number of year, Monday as the first day of week, 00-5352 
%cLocal version of date and timeMon Dec 31 17:41:00 2018 
%CCentury20 
%xLocal version of date12/31/18 
%XLocal version of time17:41:00 
%%A % character% 
%GISO 8601 year2018 
%uISO 8601 weekday (1-7)1 
%VISO 8601 weeknumber (01-53)01 

Try It Yourself: Fun Exercises

  1. Print Today's Date:
    • Use the datetime module to print today's date and time.
  2. Formatted Date Strings:
    • Create a date object for your birthday and print it in a different format using the strftime() method.

Summary:

In this Python tutorial, we learned how to work with dates using the datetime module. We explored how to get the current date and time, create date objects, and format dates into readable strings. Keep experimenting and have fun with dates in Python!