Date and Time in Python

Devendra Tiwari
0

Date and Time in Python

This article is created to provide you all the things that relates about handling of dates and times in Python programming. In this article, I've included a lot of programs with its output to provide you the better understanding about the topic in an efficient way.

What are the Things provided here ?

This article deals with:

  • Print Current Date/Time using Python
  • Get All Attributes of datetime Module
  • Count Total Seconds since 1970
  • Count Total Number of Seconds since Today's Midnight
  • Count Total Seconds required to execute any code in Python
  • Simple Date Arithmetic
  • Compute Time Difference
  • Find Next Date after Given Days
  • Find Previous Date with Given Days
  • Date/Time Format Codes with Description

The datetime Module

The datetime module in Python is used to work with dates and times.

Print Current Date/Time using Python

The program given below find and prints the current date and time using now() method of datetime attribute of datetime module.

import datetime

current_date_time = datetime.datetime.now()
print("The Current Date/Time =", current_date_time)

The snapshot given below shows the sample output produced by this Python program:

python print current date time

In above sample output:

  1. 2021 shows the year
  2. 07 shows the month number, that equals July
  3. 28 is the date of the month, that equals 28th July
  4. 13 is the hour time, that is equal to 1 PM
  5. 55 is the minute time, that equals 1.55 PM
  6. 27 is the second time, that equals 1.55.27 PM
  7. 937434 is the microsecond time, that equals 1.55.27.937434 PM

Get All Attributes of datetime Module

To get all the attributes available in datetime module, use dir method to fetch and print like shown in the program given below:

import datetime

print(dir(datetime))

The snapshot given below is nothing but the sample output produced by above program:

python get all attributes of datetime module

Note - Since all the attributes of datetime module can not be shown in one single snapshot, therefore I've listed all those attributes given below:

  • MAXYEAR
  • MINYEAR
  • __all__
  • __builtins__
  • __cached__
  • __doc__
  • __file__
  • __loader__
  • __name__
  • __package__
  • __spec__
  • date
  • datetime
  • datetime_CAPI
  • sys
  • time
  • timedelta
  • timezone
  • tzinfo

The program given below uses all the above attributes to provide you some idea about what these are used for after seeing its sample output. Let's have a look at the program first, as given below:

import datetime

print("1.", datetime.MAXYEAR)
print("2.", datetime.MINYEAR)
print("3.", datetime.__all__)
print("4.", datetime.__builtins__)
print("5.", datetime.__cached__)
print("6.", datetime.__doc__)
print("7.", datetime.__file__)
print("8.", datetime.__loader__)
print("9.", datetime.__name__)
print("10.", datetime.__package__)
print("11.", datetime.__spec__)
print("12.", datetime.date)
print("13.", datetime.datetime)
print("14.", datetime.datetime_CAPI)
print("15.", datetime.sys)
print("16.", datetime.time)
print("17.", datetime.timedelta)
print("18.", datetime.timezone)
print("19.", datetime.tzinfo)

And here is its sample output:

python datetime module attributes program

Count Total Seconds since 1970

The program given below counts total number of ticks (seconds) occurred since 12.00 AM 1970 to now (1.22.49PM, 28 July, 2021):

import time

ticks = time.time()
print("Number of Ticks since 12:00AM, January 1970 is", ticks)

The output produced by this program is shown in the snapshot given below:

python date time

Count Total Number of Seconds since Today's Midnight

This program counts total number of seconds elapsed since today's midnight, that is 12.00 AM.

import datetime

midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
current_time = datetime.datetime.now()
seconds_elapsed = current_time - midnight
print("Total Seconds elapsed since Midnight =", seconds_elapsed.seconds)

Here is the sample output produced by this program:

python count seconds elapsed since midnight

Note - Since the current time is around 1.50.02, therefore you saw this output. If you convert these seconds into hours, then you will get approx. 13 hours plus 50 minutes, then some seconds and microseconds.

Count Total Seconds required to execute any code in Python

The program given below counts the total number of time taken to execute the code written between "code start" and "code end" comment line. That is the code, print("Hello World").

import datetime

start_time = datetime.datetime.now()

# code start
print("Hello World")
# code end

end_time = datetime.datetime.now()
total_time = end_time - start_time
print("Total time taken =", total_time)

The snapshot given below shows the sample output:

python print calendar time date

We've done the job of counting total number of time taken to execute the code by:

  • I've initialized the current time to the variable named start_time
  • Execute the code whatever we want to
  • Again I've initialized the current time, but to a different variable named end_time
  • Then I've subtracted the value of start_time from end_time and initialized the subtraction result to a new variable named total_time
  • Now Prints the variable's value, that is total_time's value
  • The output will be, whatever the time gets taken to execute the code between these two codes start_time = datetime.datetime.now() and end_time = datetime.datetime.now(), in above program

Since the program given above is very simple, that is only prints a short string, therefore the time taken is 0. Now, let's create another program that takes some 1, 2, or even more seconds to execute the code in between.

import datetime

start_time = datetime.datetime.now()

print("Enter the limit: ")
lim = int(input())
for i in range(lim):
    print(i)

end_time = datetime.datetime.now()
time_taken = end_time - start_time
print("Total time taken =", time_taken)

Here is the initial output produced by above program:

python count time taken to execute program

Now provide the input say 20 to execute the loop and print the value from 0 to 19. While printing all these values, the number of time taken to evaluate the loop, will gets printed on the output after printing these values like shown in the snapshot given below:

python time calculation example by counting time

Simple Date Arithmetic Program

This program shows simple arithmetic handling of dates in Python.

import datetime

today = datetime.date.today()
print("Today's Date is", today)

yesterday = today - datetime.timedelta(days=1)
print("Yesterday's Date was", yesterday)

tomorrow = today + datetime.timedelta(days=1)
print("Tomorrow's Date will be", tomorrow)

print("Time difference between Yesterday and Tomorrow is", tomorrow - yesterday)

The snapshot given below shows the sample output of this program:

python simple date arithmetic

Compute Time Difference

The program given below compute time difference between current time and past time:

from datetime import datetime

now = datetime.now()
then = datetime(2021, 7, 23)

time_difference = now - then
print("Time Difference =", time_difference)
print("Time Difference (in days) =", time_difference.days)
print("Time Difference (in seconds) =", time_difference.seconds)

Here is its sample output. The current date is 28/07/2021 and the current time is 16:42:32

python compute time difference example

Compute Time Difference between Current and Given Time

This is the modified version of previous program. This program allows user to define the date at run-time to make program work in dynamic way. That is, whatever the date is provided by user, the program find and prints the time difference between current and given date like shown in the program and its sample run given below:

from datetime import datetime

print("Enter Date (in DD/MM/YYYY) format: ")
mydate = input()

myday = mydate[0:2]
mymonth = mydate[3:5]
myyear = mydate[6:10]

myday = int(myday)
mymonth = int(mymonth)
myyear = int(myyear)

now = datetime.now()
then = datetime(myyear, mymonth, myday)

time_difference = now - then

print("Time Difference =", time_difference)
print("Time Difference (in days) =", time_difference.days)
print("Time Difference (in seconds) =", time_difference.seconds)

Here is its initial sample output:

python compute time difference between current and given time

Now provide the date whatever you want, like I've provided the date as 10/07/2021 and pressed ENTER key. Here is the output produced:

python print time difference between given and present time

Note - Whatever user enters, the input() method of Python treats it as string. Therefore using string slicing, I've sliced the value of day, month and year. That is, 10/07/2021 inputs gets initialized to mydate variable in a way that:

  • mydate[0] = '1'
  • mydate[1] = '0'
  • mydate[2] = '/'
  • mydate[3] = '0'
  • mydate[4] = '7'
  • mydate[5] = '/'
  • mydate[6] = '2'
  • mydate[7] = '0'
  • mydate[8] = '2'
  • mydate[9] = '1'

Now the code mydate[0:2], means the character from 0th (included) index to 2th (excluded) index gets sliced. After slicing the value, we've converted into integer form using int() method and then further proceed to do the job.

Find Next Date after Given Days

This program receives number of days as input from user at run-time to find and print the date after given number of days. For example, if user enters 46 days as input, then the program will calculate and print the date that will come after 46 days from now. Let's have a look at the program given below:

from datetime import datetime, timedelta

print("Enter Total Number of Days: ")
myday = int(input())

date_after_myday = datetime.now() + timedelta(days = myday)
print("\nDate after", myday, "Days =", date_after_myday)

Since the current date is 28 July, 2021, therefore the program produces the following output after providing 46 days as input:

python print date after given days

Note - You are free to format the date using date format code. The code to format the date is given at last of this article.

Find Previous Date with Given Days

Now this is the reverse of previous program. To find the previous date with given number of days by user, just replace the following line of code:

date_after_myday = datetime.now() + timedelta(days = myday)

from previous program, with the code given below:

date_after_myday = datetime.now() - timedelta(days = myday)

Just a matter of + (plus) and - (minus), the whole program gets reversed. Here is the modified and complete version of the program:

from datetime import datetime, timedelta

print("Enter Total Number of Days: ", end="")
myday = int(input())

prev_date = datetime.now() - timedelta(days = myday)
print("\nDate before", myday, "Days = ", end="")
print(prev_date.strftime("%d"), end=" ")
print(prev_date.strftime("%b"), end=", ")
print(prev_date.strftime("%Y"))

Here is its sample output after providing 12 as input. The current date is 28 July, 2021:

python print previous date before given days

Iterate Over a Range of Dates

The program given below iterates over a range of dates. In this program, I've provided 1 as day to iterate over, that is from the current date to next 10 days, the date gets incremented by 1 day.

import datetime

dd = datetime.timedelta(days=1)
start_date = datetime.date.today()
end_date = start_date + (10*dd)
for i in range((end_date - start_date).days):
    print(start_date + i*dd)

Here is its sample output:

python iterates over dates example

Date/Time Format Codes with Description

This section includes all the essential and most useful date/time formatting codes with its description. The example program of all these codes is also given after the table.

Format CodeUsed for
%aShort version of weekday such as Mon, Tue
%AFull version of weekday such as Monday, Tuesday
%dDay of month (01-31) such as 01, 02
%bShort version of month name such as Jan, Feb
%BFull version of month name such as January, February
%mMonth as a number (01-12) such as 01, 02
%yShort version of year such as 20, 21
%YFull version of year such as 2020, 2021
%HFor hour (00-23) such as 00 (12AM), 01 (1AM), 13(1PM), 20(8PM)
%IFor hour (00-12) such as 01, 02
%pFor AM/PM
%MFor minute (00-59) such as 00, 01
%SFor second (00-59) such as 00, 01
%fFor microsecond (000000-999999) such as 000000, 000001
%jDay number of the year (001-366) such as 001, 002
%cLocal version of date and time such as Wed Jul 28 01:58:00 2021
%xLocal version of date (MM/DD/YY) such as 07/28/2021, 08/26/2021
%XLocal version of time (HH:MM:SS) such as 13:59:00

The program given below uses all the above listed directive with its example in one single program:

import datetime

cc = datetime.datetime.now()

print("Short Weekday =", cc.strftime("%a"))
print("Full Weekday =", cc.strftime("%A"))
print("Day of Month =", cc.strftime("%d"))
print("Short Month Name =", cc.strftime("%b"))
print("Full Month Name =", cc.strftime("%B"))
print("Month Number =", cc.strftime("%m"))
print("Short Year =", cc.strftime("%y"))
print("Full Year =", cc.strftime("%Y"))
print("Hour (in 24-hour Format) =", cc.strftime("%H"))
print("Hour (in 12-hour Format) =", cc.strftime("%I"))
print("AM/PM =", cc.strftime("%p"))
print("Minute =", cc.strftime("%M"))
print("Second =", cc.strftime("%S"))
print("Microsecond =", cc.strftime("%f"))
print("Day Number of Year =", cc.strftime("%j"))
print("Local Date/Time =", cc.strftime("%c"))
print("Local Date =", cc.strftime("%x"))
print("Local Time =", cc.strftime("%X"))

The snapshot given below shows sample output produced by this Python program:

python print date time format example

Note - The strftime() is a method of datetime object, used for formatting date objects into understandable and normally used date/time in daily life. This method takes one parameter that is used to format the string (date/time) like shown in the sample program and its sample output given above.

Post a Comment

0Comments
Post a Comment (0)