Python DateTime module with programs and exercises
Here in this post, you’ll learn Python DateTime module with programs and exercises.
Table of Contents
- Introduction
- Date and Time Functions
- Convert String to DateTime object and vice-versa
- Datetime format code table
- Python Date and Time programs
- Timezones and Conversions
- Conclusion
Post Update Timeline
Updated on : 03-08-2020
Added new section Timezones and Conversions with including such as show DateTime by timezones, convert DateTime of one timezone into another timezone, etc.
Introduction
By the way, Python provides a DateTime module which we’ll be using to work with date and time-related cases and also go through the simple program and learn their implementation of this module.
However, at the end of this post on the Python DateTime module with programs and exercises you’ll learn the below concepts:
- DateTime Function with programs
- Working with different Timezones using pytz library.
Date and Time Functions
Get Current Date and Time
import datetime current_date = datetime.datetime.today() print(current_date) #PYTHON OUTPUT datetime.datetime(2020, 2, 26, 12, 59, 32, 944167)
Here DateTime is module name and followed by another DateTime is a class that contains current DateTime information.
Creating a new Date and time object
from datetime import datetime my_datetime = datetime(2020,2,26,1,15,30) print(my_datetime) #PYTHON OUTPUT datetime.datetime(2020, 2, 26, 1, 15, 30)
Here we have imported datetime
class from the module. Class datetime
needs parameter through which object is created and the positional parameters are year,month,day,hour,minute,seconds
.
Convert String to DateTime object and vice-versa
from datetime import datetime my_datetime = datetime(2020,2,26,1,15,30) format = "On %d %B %Y, at %I hour %M minutes and %S seconds %p i saw you in walmart with your brother" print(my_datetime.strftime(format)) #PYTHON OUTPUT On 26 February 2020, at 01 hour 15 minutes and 30 seconds AM i saw you in walmart with your brother
Here the format includes those special characters % which will be interpreted to their respective form. Each of those will represent a particular part of the date and time.
Let’s look and another example of a string is converted to DateTime object and again back to the same string which was used as input to class DateTime.
from datetime import datetime string_datetime = "2020-02-26 8:15:45 PM" format = "%Y-%m-%d %I:%M:%S %p"; date_obj = datetime.strptime(string_datetime, format) print("Newly created DateTime object : \n") print(date_obj) date_object_back_to_string = date_obj.strftime(format) print("\nConverted datetime object back to string : {}\n".format(date_object_back_to_string)); #PYTHON OUTPUT python datetime_prog.py Newly created DateTime object : 2020-02-26 20:15:45 Converted datetime object back to string : 2020-02-26 08:15:45 PM
Here the strptime(date_string, format) method takes two arguments they are string representation of DateTime and the format of date-time which is used in this case it is string_datetime.
strftime(format) the method takes one string argument that is in which format the DateTime must be displayed. It converts DateTime object back to a string.
Datetime format code table
Python has a standardized format code for representing symbols with respective date and time representation. Some of them are given below.
Symbol | Representation |
---|---|
%a |
Represents weekday’s short name as Mon, Tue. |
%A |
Represents weekday’s full name such as Sunday, Monday. |
%w |
Represents weekday as a decimal number, where 0 is Sunday and 6 is Saturday. |
%d |
represents a decimal number of a day like 01, 15, etc. |
%b |
Represents month and displays the short name for the month such as for January as Jan, February as Feb |
%B |
Represents months full name |
%m |
Represents numerical name for the month |
%Y |
Represents full 4 characters year number |
%p |
Represents time in 12-hour format |
However, If you’re interested to learn more about DateTime format codes then click here to visit the official site for Python Programming.
Python Date and Time programs
Show month name from a given date
Program with accepts a date with a day-month-year format and returns the name of a month on a given date.
from datetime import datetime print("Enter valid date with format (day-month-year) : \n") input_date = input() date_object = datetime.strptime(input_date,"%d-%m-%Y") month = date_object.strftime("%B") print("The entered date comes in a month is: {}".format(month)) #PYTHON OUTPUT Enter valid date with format (day-month-year) : 25-03-2020 The entered date comes in a month is: March
Show number of days in the month
As an example, This program takes year and month as input from the user as numeric values and convert them into a DateTime object. However, another object is created by incrementing the month numeric value, and if the month goes above 12 then it is reassigned to one i.e first month.
from datetime import datetime print("Enter the year in format YYYY : \n") input_year = input() print("Enter month in number format : \n") input_month = input() input_date = "{}-{}".format(input_year,input_month); format = "%Y-%m" start_date_obj = datetime.strptime(input_date, format) if int(input_month) < 12: input_month = str(int(input_month)+1) else: input_month = "1" input_year = int(input_year)+1 next_input_date = "{}-{}".format(input_year, input_month) next_date_obj = datetime.strptime(next_input_date, format) difference_in_days = (next_date_obj-start_date_obj).days print("\n***************Output**********************\n") print("\nYour entered year and month is: {}".format(start_date_obj)) print("\nNext month: {}".format(next_date_obj)) print("\nThe difference in days are : {}".format(difference_in_days)) #PYTHON OUTPUT 1 $ python3.8 datetime_prog.py Enter the year in format YYYY : 2020 Enter month in number format : 1 ***************Output********************** Your entered year and month is: 2020-01-01 00:00:00 Next month : 2020-02-01 00:00:00 The difference in days are: 31 #PYTHON OUTPUT 2 $ python3.8 datetime_prog.py Enter the year in format YYYY : 2020 Enter month in number format : 2 ***************Output********************** Your entered year and month is: 2020-02-01 00:00:00 Next month : 2020-03-01 00:00:00 The difference in days are: 29
Here, the difference_in_days is calculated by subtracting two different DateTime objects.
Show next upcoming month from a given month
Takes month as a number as input from user creates DateTime object and increments the month given by the user with plus 1 which gets us the next month.
from datetime import datetime print("Enter year in format YYYY : \n") input_year = input() print("Enter month in number format : \n") input_month = input() input_date = "{}-{}".format(input_year,input_month); format = "%Y-%m" start_date_obj = datetime.strptime(input_date, format) if int(input_month) < 12: input_month = str(int(input_month)+1) else: input_month = "1" input_year = int(input_year)+1 next_input_date = "{}-{}".format(input_year, input_month) next_date_obj = datetime.strptime(next_input_date, format) difference_in_days = (next_date_obj-start_date_obj).days print("\n***************Output**********************\n") print("\nYour entered year and month is : {}".format(start_date_obj)) print("\nNext month : {}".format(next_date_obj)) print("\nDifference in days are : {}".format(difference_in_days)) #PYTHON OUTPUT 1 $ python3.8 datetime_prog.py Enter the year in format YYYY : 2020 Enter month in number format : 1 ***************Output********************** Your entered year and month is : 2020-01-01 00:00:00 Next month : 2020-02-01 00:00:00 Difference in days are : 31 #PYTHON OUTPUT 2 $ python3.8 datetime_prog.py Enter year in format YYYY : 2020 Enter month in number format : 2 ***************Output********************** Your entered year and month is: 2020-02-01 00:00:00 Next month : 2020-03-01 00:00:00 Difference in days are : 29
Timezone and Conversions
If you want to show date and time for users on basis of their timezone then in such case you must use pytz library which will help you while working with world timezones. However, in this post, we’ll be only using two libraries and they are DateTime and pytz.
As an example, the below programs are for you to understand the basic and inner workings of timezones. To begin with, an example of showing DateTime by using pytz library.
Program to get DateTime by timezones
import pytz, datetime india_kolkata_timezone = pytz.timezone('Asia/Kolkata') us_alaska_timezone = pytz.timezone('US/Alaska') india_time = datetime.datetime.now(india_kolkata_timezone) us_time = datetime.datetime.now(us_alaska_timezone) print(f""" Current Time by on Different Timezones India/Kolkata : {india_time.strftime("%d-%m-%Y %H:%M:%S %P")} Us/Alaska : {us_time.strftime("%d-%m-%Y %H:%M:%S %P")} """) #PYTHON OUTPUT Current Time by on Different Timezones India/Kolkata : 26-05-2020 10:24:43 am Us/Alaska : 25-05-2020 20:54:43 pm
Program to convert DateTime of one timezone into another timezone
Here, the timezone of Asia/Kolkata in converted to US/Alaska.
import pytz, datetime india_kolkata_timezone = pytz.timezone('Asia/Kolkata') us_alaska_timezone = pytz.timezone('US/Alaska') # Local time local_time = "26-05-2020 10:39:05 am" format = "%d-%m-%Y %H:%M:%S %p" local_datetime_object = datetime.datetime.strptime(local_time, format) # Converted time us_alaska_converted_datetime_object = local_datetime_object.astimezone(us_alaska_timezone) print(f""" Converting DateTime string to timezone Local DateTime : {local_datetime_object} Us/Alaska DateTime : {us_alaska_converted_datetime_object} """) #PYTHON OUTPUT Converting DateTime string to timezone Local DateTime : 2020-05-26 10:39:05 Us/Alaska DateTime : 2020-05-25 21:09:05-08:00
DateTime strptime() method ignore extra format of trailing part of a string
The strptime() method will convert the DateTime string into a python DateTime object.
Caution
The strptime() method will throw ValueError: unconverted data remains when encountered with an invalid DateTime string.
Example:
local_time = "26-05-2020 10:39:05 am" format = "%d-%m-%Y" local_datetime_object = datetime.datetime.strptime(local_time, format) #PYTHON OUTPUT ValueError: unconverted data remains: 10:39:05 am
However, you can suppress the error by using Try-Except Block. The right method is to pass a part of the string into DateTime object.
import pytz, datetime local_time = "26-05-2020 10:39:05 am" format = "%d-%m-%Y" local_datetime_object = datetime.datetime.strptime(local_time[0:10], format) print(local_datetime_object) #PYTHON OUTPUT 2020-05-26 00:00:00
Here is a StackOverflow thread for ignoring a part of the DateTime string from parsing.
Conclusion
You have reached the end of our post on the Python DateTime module with programs and exercise. we appreciate you for going through this post.
If you find anything difficult with our way of explanation please leave us a comment for any suggestions or queries.
Recent Posts




