Python Date and Time
Python includes the datetime module, which facilitates the manipulation of actual dates and times. This module allows us to arrange our Python scripts to execute at specified times. Although 'date' is not classified as a data type, we can handle date objects by importing the modules known as datetime, time, and calendar.
In this segment of the tutorial, we will explore the manipulation of date and time objects within Python.
The datetime classes are classified into six main classes.
- Date - It is a simple date. It consists of the year, month, and day as attributes.
- Time - It is a perfect time, assuming every day has precisely 246060 seconds. It has hour, minute, second, microsecond, and tzinfo as attributes.
- datetime - It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
- timedelta - It represents the difference between two dates, times, or datetime instances to microsecond resolution.
- tzinfo - It provides time zone information objects.
- Timezone - It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.
In Python, time is recorded beginning from 12 AM on January 1, 1970. The function time found in the time module provides the total count of ticks that have elapsed since 12 AM on January 1, 1970. A tick is regarded as the minimal unit for measuring time.
Python Tick Example
Allow us to illustrate the concept of a tick in Python through an example.
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
Output:
1585928913.6519969
How to get the current time?
The localtime functions found within the time module are utilized to retrieve the current time in the form of a tuple. Take a look at the following illustration that demonstrates how to obtain the current time by employing the localtime function.
import time;
#returns a time tuple
print(time.localtime(time.time()))
Output:
time.struct-time(tm-year=2020, tm-mon=4, tm-mday=3, tm-hour=21, tm-min=21, tm-sec=40, tm-wday=4, tm-yday=94, tm-isdst=0)
Time tuple
Time is represented as a tuple consisting of nine numerical values. Let’s examine the components of the time tuple.
| Index | Attribute | Values |
|---|---|---|
0 |
Year | 4 digit (for example 2018) |
1 |
Month | 1 to 12 |
2 |
Day | 1 to 31 |
3 |
Hour | 0 to 23 |
4 |
Minute | 0 to 59 |
5 |
Second | 0 to 60 |
6 |
Day of weak | 0 to 6 |
7 |
Day of year | 1 to 366 |
8 |
Daylight savings | -1, 0, 1 , or -1 |
Getting formatted time
Time can be presented in a specific format by utilizing the asctime function from the time module. This function provides the formatted representation of the time corresponding to the time tuple that is supplied as an argument.
Python Example to Getting Formatted Time
Let's consider an example to illustrate how to obtain formatted time in Python.
import time
#returns the formatted time
print(time.asctime(time.localtime(time.time())))
Output:
Wed Sep 10 13:52:19 2025
Python sleep time
The sleep function found in the time module serves to pause the running of the script for a specified duration. The output will be postponed for the number of seconds specified as a floating-point number.
Python sleep time Method Example
To illustrate the use of the sleep time method in Python, let’s consider an example.
import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
time.sleep(1)
Output:
0
1
2
3
4
The datetime Module
The datetime module allows for the creation of personalized date objects and facilitates a variety of operations on dates, including comparison tasks. To utilize dates as date objects, it is essential to import the datetime module into your Python source code.
Python datetime Module Example
Take a look at the following example to obtain the datetime object that represents the current moment.
import datetime
#returns the current datetime object
print(datetime.datetime.now())
Output:
2025-09-10 13:54:25.140259
Creating date objects
Date objects can be instantiated by supplying the specific date to the datetime constructor, which is responsible for generating the desired date objects.
Python Example to Create Date Objects
In this section, we will explore an example that illustrates how to generate date objects in Python.
import datetime
#returns the datetime object for the specified date
print(datetime.datetime(2025,9,10))
Output:
2025-09-10 00:00:00
Python datetime Module Example with Custom Date and Time
Additionally, we have the option to include time alongside the date when constructing a datetime object. Refer to the example below.
import datetime
#returns the datetime object for the specified time
print(datetime.datetime(2025,9,10,1,58,20))
Output:
2025-09-10 01:58:20
Explanation:
In the code provided above, we have sequentially supplied the year, month, day, hour, minute, and millisecond parameters to the datetime function.
Comparison of two dates
We can evaluate two dates by employing comparison operators such as >, >=, <, and <=.
Python Example for Comparing Two Dates
To illustrate the process of comparing two dates in Python, we can utilize an example.
from datetime import datetime as dt
#Compares the time. If the time is in between 8 AM and 4 PM, then it prints working hours; otherwise, it prints fun hours
if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now().day,16):
print("Working hours....")
else:
print("fun hours")
Output:
Working hours....
Calendar module
Python offers a calendar object that includes multiple methods for managing and interacting with calendars.
Calender Module Example in Python
Examine the subsequent illustration for displaying the calendar for December of the year 2018.
import calendar;
cal = calendar.month(2025,9)
#printing the calendar of December 2018
print(cal)
Output:
Printing the calendar for the whole year
The prcal function within the calendar module is utilized to display the calendar for a full year. It is essential to provide the specific year for which the calendar should be generated as an argument to this method.
import calendar
#printing the calendar of the year 2025
s = calendar.prcal(2025)
Output:
Python Date and Time FAQs
1. Which module is used for handling dates and times in Python?
Python offers the datetime module, which facilitates working with actual dates and times. This functionality allows us to set a specific time for our Python script to execute.
We import the data and time module by:
import datetime
2. How do we get the current date and time?
To retrieve the present date and time, you can utilize the code shown below:
from datetime import datetime
now = datetime.now()
print(now)
Output:
2025-08-28 06:19:46.145852
3. How do we format dates in Python?
In Python, the .strftime function allows us to format dates effectively.
from datetime import datetime
now = datetime.now()
#using the .strftime() method
print(now.strftime("%d-%m-%Y %H:%M:%S"))
Output:
28-08-2025 06:39:25
4. What are some common strftime format codes?
Some common strftime format codes are:
- %d: It represents the Day of month
- %m: It represents the Month
- %Y: It represents the Year
- %H: It represents the Hour (24-hour format)
- %M: It represents the Minute
- %S: It represents the Second
- %A: It represents the Full weekday name( for example, Monday)
- %B: It represents the Full month name (for example, August)
5. What's the difference between datetime.now and datetime.utcnow?
The primary distinction between datetime.now and datetime.utcnow lies in the following aspects:
- now returns the current local date and time.
- utcnow returns the current time in UTC, which stands for Coordinated Universal Time.