Page Contents
Python datetime module
The datetime
module in Python provides classes for manipulating dates and times. Here’s a quick overview of the most commonly used classes and methods in the datetime
module:
Classes
datetime.date
: Represents a date (year, month, and day).datetime.time
: Represents a time (hour, minute, second, microsecond).datetime.datetime
: Represents both date and time.datetime.timedelta
: Represents the difference between two dates or times.datetime.tzinfo
: A base class for dealing with time zones.
Example1 – Getting current date and time.
import datetime # Current date and time now = datetime.datetime.now() print(now) # Current date today = datetime.date.today() print(today) # Output 2024-06-14 16:39:48.511139 2024-06-14
Example2 – Creating a specific date or time using date class.
# Creating a specific date my_date = datetime.date(2024, 6, 14) print(my_date) # Creating a specific time my_time = datetime.time(17, 7, 45) print(my_time) # Creating a specific datetime my_datetime = datetime.datetime(2024, 6, 14, 17, 7, 45) print(my_datetime) # Output 2024-06-14 17:07:45 2024-06-14 17:07:45
Example3 – Formatting date using strftime()
import datetime # Get the current date and time current_date = datetime.datetime.now() print("current_date: ", current_date) formatted_date = current_date.strftime("%Y-%m-%d %H:%M:%S") print("formatted_date: ", formatted_date) # Output current_date: 2024-06-14 17:18:56.158331 formatted_date: 2024-06-14 17:18:56
In this example, %Y-%m-%d %H:%M:%S
is the format string used with strftime
to specify how the date and time should be formatted:
%Y
: Year with century (e.g., 2024)%m
: Month as a zero-padded decimal number (e.g., 06)%d
: Day of the month as a zero-padded decimal number (e.g., 14)%H
: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13)%M
: Minute as a zero-padded decimal number (e.g., 30)%S
: Second as a zero-padded decimal number (e.g., 45)
More examples of strftime()
current_date = datetime.datetime.now() print("current_date: ", current_date) # Example 1: "Month Day, Year Hour:Minute AM/PM" formatted_date1 = current_date.strftime("%B %d, %Y %I:%M %p") print("formatted_date1:", formatted_date1) # Example 2: "Day-Month-Year Hour:Minute:Second" formatted_date2 = current_date.strftime("%d-%m-%Y %H:%M:%S") print("formatted_date2:", formatted_date2) # Example 3: "Weekday, Month Day, Year" formatted_date3 = current_date.strftime("%A, %B %d, %Y") print("formatted_date3:", formatted_date3) # Example 4: "Year-Month-Day" formatted_date4 = current_date.strftime("%Y-%m-%d") print("formatted_date4", formatted_date4) # Output current_date: 2024-06-14 17:26:47.417532 formatted_date1: June 14, 2024 05:26 PM formatted_date2: 14-06-2024 17:26:47 formatted_date3: Friday, June 14, 2024 formatted_date4 2024-06-14
These examples show how flexible and powerful the strftime
method can be for formatting dates and times in Python.