Python datetime() tutorial with examples

In this tutorial we will learn about python datetime() module. The standard datetime module handles dates and times. It defines four main object classes, each with many methods:

  • date for years, months, and days
  • time for hours, minutes, seconds, and fractions
  • datetime for dates and times together
  • timedelta for date and/or time intervals

 

List the available class from python datetime module

We can use dir(datetime) to list the supported operations under this module, or you can use the same method to check operations supported by sub module of datetime function.

 

Example: Print in-built module and sub-modules from datetime

In this script I will just print the content of datetime() and datetime.datetime() modules.

#!/usr/bin/env python3

# Import the datetime module
import datetime

# List sub modules (operations) under datetime module
print("content of datetime module: ",dir(datetime))

# List operations under datetime.datetime sub module
print("\ncontent of datetime.datetime submodule: ",dir(datetime.datetime))

Output from this script:

# python3 /tmp/datetime_ex.py
content of datetime module:  ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

content of datetime.datetime submodule:  ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']

 

Using datetime.now()

The datetime.now() function returns the current local date and time. There are various sub modules which you can use with datetime.now() to list different values such as month, year, date etc.

Example: Get current date and time from local machine

In this example python script we will print different operations supported by datetime.now()

#!/usr/bin/env python3

import datetime

# print current date and time based on the timezone from local machine
print("Year: ",datetime.datetime.now().year)
print("Month: ",datetime.datetime.now().month)
print("Day: ",datetime.datetime.now().day)
print("Hour: ",datetime.datetime.now().hour)
print("Minute: ",datetime.datetime.now().minute)
print("Second: ",datetime.datetime.now().second)

Output:

# python3 /tmp/datetime_ex.py
Year:  2020
Month:  6
Day:  11
Hour:  8
Minute:  59
Second:  35

 

Python datetime() to string format using strftime()

You can also format the output from datetime() module into string form by using strftime() which is pronounced as "string format time"

I have summarised some of the most used code format, but to get the complete list of symbols and their meaning for datetime(), you can refer https://strftime.org/

ArgumentMeaningRange
%aWeekday name, short versionSun
%AWeekday name, full versionSunday
%wWeekday as number, 0 is Sunday0 - 6
%bMonth name, shot versionJan
%BMonth name, full versuibJanuary
%mMonth01-12
%dDay of the month01 - 31
%YFour-digit year, full version2019
%yTwo-digit year, short version19
%HHour, in 24-hour format00 - 23
%IHour, in 12-hour format01 - 12
%pAM or PMAM, PM
%MMinutes00 - 59
%SSeconds00 - 59
%ZTimezoneIST
%cLocal version of date and timeThu 11 Jun 2020 08:42:30 AM IST>/code>
%XLocal version of time08:43:07 AM
%xLocal version of date06/11/2020

 

Example: Use strftime() to format datetime()

In this script we will use strftime() to format different datetime.now() values

#!/usr/bin/env python3

from datetime import datetime

current_date_time = datetime.now()

print("Current date and time: ",current_date_time)

only_time = datetime.now().strftime("%H-%M-%S")
print("Only Time output: ", only_time)

only_date = datetime.now().strftime("%d-%m-%Y")
print("Only Date output: ",only_date)

date_and_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
print("Date and Time: ",date_and_time)

Output:

# python3 /tmp/datetime_ex.py
Current date and time:  2020-06-20 16:19:00.766771
Only Time output:  16-19-00
Only Date output:  20-06-2020
Date and Time:  2020-06-20 16:19:00.767143

 

Python string to datetime() using striptime()

Strings can be converted (parsed) into datetime objects with the strptime() function:

 

Example: Convert string type datetime()

In this script we will convert dateString object which contains a string type value to datetime() type value.

#!/usr/bin/env python3

import datetime

# Define a string variable
dateString = "20-06-2020"

# Print and check the type of object for dateString
print("Defined date string: ",dateString)
print("Type of daeString object: ",type(dateString),"\n")

# Convert to datetime type
new_object = datetime.datetime.strptime(dateString, "%d-%m-%Y")

# Print and check the type of new_object
print("New object: ",new_object)
print("Type of new_object: ",type(new_object))

Output:

# python3 /tmp/datetime_ex.py
Defined date string:  20-06-2020
Type of daeString object:  <class 'str'>

New object:  2020-06-20 00:00:00
Type of new_object:  <class 'datetime.datetime'>

 

Python datetime timezone

Python provides two ways of accomplishing time zone conversions. The old way, using the time built-in module, is terribly error prone. The new way, using the datetime built-in module, works great with some help from the community-built package named pytz

 

Example: Use datetime.timezone()

In this script we will convert the timezone from datetime.now() to UTC timezone

#!/usr/bin/env python3

import datetime

print("Local Date and Time: ",datetime.datetime.now())
print("Current Date and Time for UTC Timezone: ",datetime.datetime.now(datetime.timezone.utc))

We can also write this script in the following format, by importing only the required sub module from datetime module

#!/usr/bin/env python3

from datetime import datetime, timezone

print("Local Date and Time: ",datetime.now())
print("Current Date and Time for UTC Timezone: ",datetime.now(timezone.utc))

Output:

# python3 /tmp/datetime_ex.py
Local Date and Time:  2020-06-20 15:31:34.638168
Current Date and Time for UTC Timezone:  2020-06-20 10:01:34.638245+00:00

 

Example: Use datetime() with pytz()

In this python script I will use pytz() module instead of timezone() to change the timezone value from datetime.now()

#!/usr/bin/env python3

from datetime import datetime
import pytz

# Store the timezone information in mytz object
mytz = pytz.timezone('UTC')

# print current date and time based on the timezone from local machine
print("Local Date and Time: ",datetime.now())

# print current date and time from UTC timezone
print("Current Date and Time for UTC Timezone: ",datetime.now(mytz))

Output from this script:

# python3 /tmp/datetime_ex.py
Local Date and Time:  2020-06-20 15:30:16.581239
Current Date and Time for UTC Timezone:  2020-06-20 10:00:16.581377+00:00

 

Example: Find all the files older than 3 days

We will write a small script to find all the files which are older than 3 days under the provided path. This script will take the input from user for target location to search for the files.

#!/usr/bin/env python3

import os
import sys
import datetime

dirpath=input("Enter your path: ")
if not os.path.exists(dirpath):
    print("Please provide valid path ")
    sys.exit(1)

if os.path.isfile(dirpath):
    print("Please provide directory path ")
    sys.exit(2)

# Create an object with current date and time
todayDate = datetime.datetime.now()
# Age reference required for comparison
age = 3

# Run a loop for individual file found under dirpath object
for myFile in os.listdir(dirpath):
    # Join the path along with the filename
    filePath=os.path.join(dirpath,myFile)
    # make sure the found element is a file
    if os.path.isfile(filePath):
        # use os.path.ctime to get creation details, or os.path.mtime for modification details
        # The value will be in seconds
        fileCrDate=os.path.getctime(filePath)
        # using fromtimestamp from datetime we get the difference by substracting from current date
        # Show only in days format from datetime module
        timeDiff=(todayDate - datetime.datetime.fromtimestamp(fileCrDate)).days
        # If the number of days in timeDiff is greater than provided age
        if timeDiff > age:
            print("No of day since",myFile,"was created:",timeDiff)

Output:

# python3 /tmp/datetime_ex.py
Enter your path: /root/scripts
No of day since large_file was created: 10
No of day since create_enum.py was created: 5
No of day since check_string.py was created: 5

 

Conclusion

In this tutorial we learned about different class under datetime() module which can be used to manipulate date and time including their timezone. This module is widely used by Linux Administrators for their day to day tasks such as locating old files, assigning timestamp to log files etc.

I could not cover many other sub modules from the datetime() module but as explained in this tutorial, you can use dir(datetime) to list the content of this module and then try to use them. Lastly I hope this programming guide on python datetime() module was helpful. So, let me know your suggestions and feedback using the comment section.

 

References

I have used below external references for this tutorial guide
python.org datetime()

 

Leave a Comment

Please use shortcodes <pre class=comments>your code</pre> for syntax highlighting when adding code.