Date and Time in Python

Date and Time in Python

In this post, we will discuss the Date and Time in Python.

Time is very precious in our lives. If utilized well, time can give us a fortune. That’s why dates, years and times are significant in the lives of humankind. Time is also essential in our daily life to calculate the metrics of individual performances. For instance, you can give the best team member award to the one in your organization who comes on time and leaves on time.

Since you and I are here due to our love of the Python programming language, it is very significant to know how you can use the Date and Time in your Python programs. In Python, you can use three modules – datetime, time, and calendar to work with the calendars, durations, times, and dates.

  • The datetime class deals with a combination of date and time. It has attributes such as tzinfo, microsecond, second, minute, hour, day, month, and year.
  • The date class deals with the Gregorian calendar dates without considering time zone information. This class has attributes such as day, month, and year.
  • The time class deals with the assumption that every single day has precisely 24 X 60 X 60 seconds.
  • The timedelta class helps deal with the durations. For those who don’t know the duration, it is the difference between two times, date or datetime instances.

The epoch

The point where the time starts is called the ‘epoch‘. This point is taken as the current year’s 0.0 hours of Jan 1. It is 0.0 hours from Jan 1 of 1970 for Unix. You can calculate the time in seconds since the epoch using the time() function of the time module.

Let us look at a program now to obtain date and time from the epoch time.

#Python program to obtain date and time from epoch

#import the time module
import time

#find the epoch in seconds
epoch = time.time()
print("Epoch value: ",epoch)
#localtime() changes the epoch time into time_struct object t
t = time.localtime(epoch)

#get date from the structure t
d = t.tm_mday
m = t.tm_mon
y = t.tm_year
print("The present date is: %d - %d - %d"%(d,m,y))

#get time from the structure t
h = t.tm_hour
m = t.tm_min
s = t.tm_sec
print("Present time is: %d:%d:%d"%(h,m,s))
Output:

Epoch value:  1655735106.1108694
The present date is: 20 - 6 - 2022
Present time is: 19:55:6

In the above program, we import the time module and find the epoch value using time.time(). This value is usually a large number like 1655735106.1108694, as shown in the output above.

We then create a time_struct object ‘t‘ using localtime() into which we pass the epoch value. This localtime() function returns a struct-like object. We can access the attributes of this object, such as tm_year, tm_mon, and tm_mday for the year, month, and day respectively.

You can notice in the program above that we used each attribute required for the date and time sections and finally printed the current time. You might get a different value and time since you will be running this program only later. However, if you pass the same epoch value from the output above, you will get the exact date and time values mentioned above.

Let us now look at all the attributes of the indexes in the ‘struct_time‘.

IndexAttributeValues
0tm_year4 digit value for year such as 2022
1tm_monrange[1,12]
2tm_mdayrange[1,31]
3tm_hourrange[0,23]
4tm_minrange[0,59]
5tm_secrange[0,61] containing leap seconds
6tm_wdayrange[0,6] Monday is 0
7tm_ydayrange[1,366]
8tm_isdst[0,1 or -1], 0 = no DST, 1 = DST is in effect, -1 = unknown
 tm_zoneName of timezone

You can also convert the epoch time into time and date using the ctime() function, as shown in the program below.

#Python program to show date and time from epoch
#using ctime() function

#import the time module
import time

epoch = time.time()
print("Epoch value is: ",epoch)
t = time.ctime(epoch)
print(t)
Output:

Epoch value is:  1655735185.725441
Mon Jun 20 19:56:25 2022

Date and Time Now

You can know the current date and time on your computer using the below.

  • The today() method of ‘datetime‘ class of ‘datetime‘ module
  • The now() method of ‘datetime‘ class of ‘datetime‘ module
  • The ctime() function of ‘time‘ module

Let us look at a program to understand how we can retrieve date and time using the today() method, now() method and ctime() function.

#Python program to display date and time using today() method
#now() method and ctime() method

#importing the datetime module for today() and now() methods
from datetime import *

#TODAY METHOD
#today from date class provides only date
todayday = date.today()
print("Date today: ",todayday)

#today from datetime class provides both date and time
todaytime = datetime.today()
print("Date and time of today: ",todaytime)

#NOW METHOD
now_value = datetime.now()
print(now_value)

print("Formatted date: {}/{}/{}".format(now_value.day,now_value.month,now_value.year))
print("Formatted time: {}:{}:{}".format(now_value.hour,now_value.minute,now_value.second))

#ctime() METHOD
#import time module
import time
t = time.ctime()
print("time from ctime without epoch: ",t)
Output:

Date today:  2022-06-20
Date and time of today:  2022-06-20 19:57:53.904144
2022-06-20 19:57:53.905182
Formatted date: 20/6/2022
Formatted time: 19:57:53
time from ctime without epoch:  Mon Jun 20 19:57:53 2022

In the program above, we displayed the date and time using today(), now() and ctime(). Please refer to the program and output above to understand the main differences between each method.

How to combine Date and Time in Python?

You can develop a ‘datetime‘ class object to combine the ‘date‘ class object and the ‘time‘ class object by relying on the combine() method. Please note that the ‘date‘ and ‘time‘ classes are from the ‘datetime‘ module. Let us now look at a program to combine date and time.

#Python program to combine date and time

#import the datetime module
from datetime import *
d = date(2022,5,15)
t = time(16,45)
dtcombined = datetime.combine(d,t)
print(dtcombined)
Output:

2022-05-15 16:45:00

You can notice in the program above that after creating separate date and time objects; we combined them using the datetime.combine() method. The output displays the date and time mentioned in the program.

How to format dates and times?

You can format the contents of the ‘datetime‘, ‘date‘, and ‘time‘ classes objects by relying on the strftime() method. Before going through the programs, let us look at the format codes you can mention in the strftime() method.

Format codeDescriptionExample
%%A single % character%
%XRepresentation of appropriate time21:30:00 (en_US)
%xRefers to the appropriate date8/16/1988 (en_US); 8/16/88 (None)
%cRefers to date and timeThu Aug 18 22:30:00 1988
%WThe week’s number in a year represented in decimals. (Monday to be considered as the first day of the week.) The days preceding the first Monday will fall under week zero.00,01,..53
%UThe week’s number in a year represented in zero-padded decimal numbers. (Sunday to be considered as the first day of the week). The days before the first Sunday fall under week zero.00,01,..53
%jThe day of the year represented as a zero-padded decimal number001, 002 .. 366
%ZName of the time zoneCST, EST etc
%fMicrosecond represented as a decimal number, padded zeroes on the left000000, 000001 .. 999999
%SThe second represented as a zero-padded decimal number00,01,..59
%MMinute represented as a zero-padded decimal number00,01, .. 59
%pAM or PMAM, PM
%I12 Hour clock as a zero-padded decimal number01,02 .. 12
%HThe 24-hour clock as a zero-padded decimal number00,01, .. 23
%YThe year with century as a decimal number0001, 0002 .. 2022 .. 9999
%yThe year without century as a zero-padded decimal number00, 01, … 99
%mMonth as a zero-padded decimal number01, 02, .. 12
%BMonth represented in full namesJanuary, February,… December
%bMonth in the short formJan, Feb .. Dec
%dDay of the month as zero-padded decimal01,02..31
%wWeekday represented in a decimal number, where 0 is Sunday, and 6 is Saturday0,1,..6
%AWeekday in full nameSunday, Monday .. Saturday
%aWeekday in the short formSun, Mon, .. Sat

Let us now look at the program to understand how we can use these formats in the strftime() method

#Program to find the day of the year using strftime() method and the formats
#also to find the weekday name

#import the datetime module
from datetime import *

#obtain today's date
todaysdate = date.today()
print("Full content in todaysdate variable: ",todaysdate)

#to use %j to return the day of the year as zero padded decimal number
strf1 = todaysdate.strftime("%j")
print("Today is {}th day of the present year".format(strf1))

#to use %A to return the weekday in fullname
strf2 = todaysdate.strftime("%A")
print("The current weekday is: {}".format(strf2))
Output:

Full content in todaysdate variable:  2022-06-20
Today is 171th day of the present year
The current weekday is: Monday

You can notice in the program above that we used the formats’ %j‘ and ‘%A‘ within the strftime() method to retrieve the day of the year and the weekday name, respectively. Similarly, you can use the other formats mentioned in the table above based on your requirements.

Let us now look at a program that can show the difference between two dates in the number of months, weeks, and days.

#Python program to show the difference between two dates
#in the form of days, weeks and months

from datetime import *

#ask user to enter two dates from the keyboard
date1,month1,year1 = [int(x) for x in input("Please enter first date: ").split('/')]
date2,month2,year2 = [int(x) for x in input("Please enter second date: ").split('/')]

#create date class objects from the entered input
dateobj1 = datetime(year1,month1,date1)
dateobj2 = datetime(year2,month2,date2)

#find difference between two dates
daysdiff = dateobj1-dateobj2
print("Difference in days: ",daysdiff)

#get difference in weeks
weeksdiff,days = divmod(daysdiff.days,7)
print("Difference in weeks: ",weeksdiff)

#difference in months
months,days = divmod(daysdiff.days,30)
print("Difference in months: ",months)
Output:

Please enter first date: 30/03/1993
Please enter second date: 20/12/1992
Difference in days:  100 days, 0:00:00
Difference in weeks:  14
Difference in months:  3
  • In the program above, we prompted user to enter the dates from the keyboard. The entered dates were later converted using the datetime() class object and stored in daysdiff.
  • The difference between the dates is returned as an object belonging to the ‘timedelta‘ class. This class has three attributes such as days, seconds, and microseconds. It means you can get the days using daysdiff.days in our program.
  • We used the divmod() method to get only the quotient in our result when divided by 7 or 30, as shown in the program above.

How to find durations using timedelta class?

We already saw a program above on finding the difference between two dates using the ‘timedelta‘ class. However, it is also possible to find the previous or future dates using the ‘timedelta‘. The object of the ‘timedelta‘ class is available in the following format.

timedelta(days-0, seconds=0, microseconds=0, milliseconds-0, minutes=0, hours=0, weeks=0)
  1. The arguments you can pass to the ‘timedelta’ class object are optional; if you do not give any argument, the value will default to 0.
  2. The arguments can be floats or integers, negative or positive.
  3. Only microseconds, seconds, and days are stored within the ‘timedelta‘ object. The arguments are converted to those units as mentioned below.

A week gets converted to 7 days

An hour to 3600 seconds

A minute to 60 seconds

A millisecond to 1000 microseconds

Let us now look at a program to obtain a future date and time based on the current date and time.

#Python program to find the future date and time

from datetime import *

#store the date and time in datetime object: date1
date1 = datetime(2022,5,14,14,30,0)

#define the duration using the timedelta object: p1
p1 = timedelta(days=10,seconds=10,minutes=20,hours=12)

#add d"uration to the date1 and print the output
print("The new date and time is: \n",date1+p1)
Output:

The new date and time is:
 2022-05-25 02:50:10

In the program above, we found a future date and time for a current date using the ‘timedelta’ object.

How to compare the two dates?

You can compare the two ‘date‘ class objects just like you compare two numbers. For example, you can use ‘date1>date2’ or ‘date1<date2’ or ‘date1==date2’ to compare date1 and date2. These comparison expressions return either True or False. Let us now look at a program to compare two dates of birth and find who’s older.

#Python program to find who is older

from datetime import *

#obtain date of births from the keyboard
da1, mo1, ye1 = [int(x) for x in input("Enter date of birth of first person: ").split('/')]
da2, mo2, ye2 = [int(x) for x in input("Enter date of birth of second person: ").split('/')]

#convert into date class objects
date1 = datetime(ye1,mo1,da1)
date2 = datetime(ye2,mo2,da2)

#compare the date of births
if date1==date2:
  print("Both the individuals share the same age")
elif date1>date2:
  print("The second person is elder to first person")
else:
  print("The first person is elder to second person")
Output:

Enter date of birth of first person: 30/03/1993
Enter date of birth of second person: 20/12/1992
The second person is elder to first person

In the program above, we accepted the date of birth as input from the keyboard to convert the entered dates into datetime objects for comparison. Based on the entered dates, the results appeared in the output as shown above.

How to sort the dates?

The popular way to sort a group of dates is to save them into a list and then use the sort() method available for the lists. The append() method can store the date class objects.

Let us look at a program to understand how we can implement this in the real world.

#Python program to sort the dates

from datetime import *

from numpy import append

#create an empty list
dategroup = []

#add today's date to empty list
dategroup.append(date.today())

#create additional dates and add them to the list
date1 = date(2022, 5, 20)
date2 = date(2020, 5, 22)

dategroup.append(date1)
dategroup.append(date2)

#sort the list
dategroup.sort()

#display the dates after sorting
print("The dates after sorting: ")
for every_date in dategroup:
  print(every_date)
Output:

The dates after sorting:
2020-05-22
2022-05-20
2022-06-20

How to work with the calendar module?

You can use the calendar month to create a calendar for any year or month. It is also helpful in determining the leap year for a given year.

Let us look at a program to find if a year entered from the keyboard is a leap year or not.

#Python program to check if an year is leap year or not

from calendar import *

year = int(input("Enter any year: "))

if (isleap(year)):
  print("{} is a leap year".format(year))
else:
  print("{} is not a leap year".format(year))
Output:

Enter any year: 2022
2022 is not a leap year

Enter any year: 2020
2020 is a leap year

You can see in the output above that it identified and displayed the leap years correctly. We used the isleap() function to determine if a year is a leap year or not.

Let us look at a program to display the calendar of a particular month.

#Python program to display the calendar of a given month

from calendar import *

#obtain the month and year from the keyboard
y = int(input("Please enter year: "))
m = int(input("Please enter month: "))

#display the calendar for the entered month and year
finalcalendar = month(y,m)

print(finalcalendar)
Output:

Please enter year: 2022
Please enter month: 06
     June 2022
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

You can see in the program above that it displayed the calendar accurately for the entered month and year.

If you want to display the calendar for an entire year, follow the format mentioned below.

calendar(year, w=2, l=1, c=6, m=3)

In the format mentioned above, the year is the particular year for which you want to see the calendar, ‘w‘ refers to the width between the columns, ‘l‘ refers to the lines between the rows, ‘c‘ refers to the column-wise space between months, and ‘m‘ refers to the number of months in a row. Let us look at a program to print the calendar for an entire year.

#Python program to display calendar for an entire year

from calendar import *

yy = int(input("Please enter year: "))
print(calendar(yy,2,1,8,3))
Output:

Please enter year: 1993
                                    1993

      January                     February                     March
Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
             1  2  3         1  2  3  4  5  6  7         1  2  3  4  5  6  7
 4  5  6  7  8  9 10         8  9 10 11 12 13 14         8  9 10 11 12 13 14
11 12 13 14 15 16 17        15 16 17 18 19 20 21        15 16 17 18 19 20 21
18 19 20 21 22 23 24        22 23 24 25 26 27 28        22 23 24 25 26 27 28
25 26 27 28 29 30 31                                    29 30 31

       April                        May                         June
Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
          1  2  3  4                        1  2            1  2  3  4  5  6
 5  6  7  8  9 10 11         3  4  5  6  7  8  9         7  8  9 10 11 12 13
12 13 14 15 16 17 18        10 11 12 13 14 15 16        14 15 16 17 18 19 20
19 20 21 22 23 24 25        17 18 19 20 21 22 23        21 22 23 24 25 26 27
26 27 28 29 30              24 25 26 27 28 29 30        28 29 30
                            31

        July                       August                    September
Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
          1  2  3  4                           1               1  2  3  4  5
 5  6  7  8  9 10 11         2  3  4  5  6  7  8         6  7  8  9 10 11 12
12 13 14 15 16 17 18         9 10 11 12 13 14 15        13 14 15 16 17 18 19
19 20 21 22 23 24 25        16 17 18 19 20 21 22        20 21 22 23 24 25 26
26 27 28 29 30 31           23 24 25 26 27 28 29        27 28 29 30
                            30 31

      October                     November                    December
Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
             1  2  3         1  2  3  4  5  6  7               1  2  3  4  5
 4  5  6  7  8  9 10         8  9 10 11 12 13 14         6  7  8  9 10 11 12
11 12 13 14 15 16 17        15 16 17 18 19 20 21        13 14 15 16 17 18 19
18 19 20 21 22 23 24        22 23 24 25 26 27 28        20 21 22 23 24 25 26
25 26 27 28 29 30 31        29 30                       27 28 29 30 31

You can see in the output above that it printed the calendar of the year accurately. Using this way, you can print the calendar of any year.

Scroll to Top