Updated On : May-09,2020 Time Investment : ~15 mins

Python datetime Module With Examples

Table Of Content

  1. Do You Want To Know Some Of The Different Functions In 'Date' Class
  2. Example 1: Get Current Date and Time
  3. Example 2: Understanding The dir()
  4. Example 3: Date object to represent a date
  5. Example 4. Learning To Get Current Date From Timestamp
  6. Example 5: Print today's year, month and day
  7. Example 6: Using 'Time' Object To Represent Time
  8. Example 7: Print Hour, Minute, Second And Microsecond
  9. Example 8: Making Use Of 'Datetime' module with 'dateclass'
  10. Example 9: Getting The Year, Month, Hour, Minute By Using timestamp
  11. Example 10: Learning To Print The Difference Between Two Dates and Times
  12. Example 11: Difference Between Two 'timedelta' objects
  13. Example 12: Time Duration In Seconds
  14. Example 13: Format date using strftime()

In Python language, the date and time are not the data type o their own but the datatime module provided by python can be imported to work with the 'date' and 'time'. The Datetime module is directly build into Python hence there would be no need to install it externally.

Datetime module in python supplies classes to work with date and time. These python classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps.

The datetime classes are categorized into 6 main classes –

  • date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day.
  • time – An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
  • datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
  • timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
  • tzinfo – It provides time zone information objects.
  • timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC
# Python program to 
# demonstrate date class 

# import the date class 
from datetime import date

# initializing constructor 
# and passing arguments in the 
# format year, month, date 
my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)

# Uncommenting my_date = date(1996, 12, 39) 
# will raise an ValueError as it is 
# outside range 

# uncommenting my_date = date('1996', 12, 11) 
# will raise a TypeError as a string is 
# passed instead of interger 
Date passed as argument is 1996-12-11

Current date

To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually.

# Python program to 
# print current date 

from datetime import date

# calling the today 
# function of date class 
today = date.today()

print("Today's date is", today)

# Printing date's components 
print("Date components", today.year, today.month, today.day)
Today's date is 2020-05-07
Date components 2020 5 7

Do You Want To Know Some Of The Different Functions In 'Date' Class.

  • fromtimestamp(timestamp): Return the local date corresponding to the POSIX timestamp
  • fromordinal(ordinal): Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
  • fromisoformat(date_string): Return a date corresponding to a date_string given in the format YYYY-MM-DD
  • fromisocalendar(year, week, day): Return a date corresponding to the ISO calendar date specified by year, week and day.

Understanding The Time Object

Time object represents local time, independent of any day. Constructor Syntax:

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

0 <= hour < 24 0 <= minute < 60 0 <= second < 60 0 <= microsecond < 1000000 fold in [0, 1]

Example 1: Get Current Date and Time

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)
2020-05-10 15:27:14.562891

To Understand what is inside the datetime module we will be making use of dir() function.This function will get a list containing all attributes of a module.

Example 2: Understanding The dir()

import datetime

print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

datetime.date Class

You can easily instantiate date objects from the 'date' class. A 'date object' generally represents a date (year, month and day).

Example 3: Date object to represent a date

import datetime

d = datetime.date(2019, 4, 13)
print(d)
2019-04-13

Understanding the use of 'date' when it is imported from the 'datetime' module

from datetime import date

a = date(2019, 4, 13)
print(a)
2019-04-13

Learning to get the currect date from class method today()

from datetime import date

today = date.today()

print("Current date =", today)
Current date = 2020-05-10

Example 4. Learning To Get Current Date From Timestamp

timestamp:

## Get date from a timestamp


from datetime import date

timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)
Date = 2012-01-11

Example 5: Print today's year, month and day

We can get year, month, day, day of the week etc. from the date object easily. Here's how:

from datetime import date

# date object of today's date
today = date.today()

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
Current year: 2020
Current month: 5
Current day: 10

datetime.time

A time object instantiated from the time class represents the local time.

Example 6: Using 'Time' Object To Represent Time

from datetime import time

# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)

# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b)

# time(hour, minute and second)
c = time(hour = 11, minute = 34, second = 56)
print("c =", c)

# time(hour, minute, second, microsecond)
d = time(11, 34, 56, 234566)
print("d =", d)
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566

Example 7: Print Hour, Minute, Second And Microsecond

from datetime import time

a = time(11, 34, 56)

print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)
hour = 11
minute = 34
second = 56
microsecond = 0

datetime.datetime

The datetime module has a class named dateclass that can contain information from both date and time objects.

Example 8: Making Use Of 'Datetime' module with 'dateclass'

from datetime import datetime

#datetime(year, month, day)
a = datetime(2018, 11, 28)
print(a)

# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)
2018-11-28 00:00:00
2017-11-28 23:55:59.342380

Example 9: Getting The Year, Month, Hour, Minute By Using timestamp

from datetime import datetime

a = datetime(2017, 11, 28, 23, 55, 59, 342380)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
year = 2017
month = 11
hour = 23
minute = 55
timestamp = 1511893559.34238

datetime.timedelta

A timedelta object represents the difference between two dates or times.

Example 10: Learning To Print The Difference Between Two Dates and Times

from datetime import datetime, date

t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)

t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5
print("t6 =", t6)

print("type of t3 =", type(t3))
print("type of t6 =", type(t6))
t3 = 201 days, 0:00:00
t6 = -333 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>

Example 11: Difference Between Two 'timedelta' objects

from datetime import timedelta

t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2

print("t3 =", t3)
t3 = 14 days, 13:55:39

Example 12: Time Duration In Seconds

from datetime import timedelta

t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)
print("total seconds =", t.total_seconds())
total seconds = 435633.233423

Python format datetime

The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.

Python has strftime() and strptime() methods to handle this.

Example 13: Format date using strftime()

from datetime import datetime

# current date and time
now = datetime.now()

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
time: 15:54:33
s1: 05/10/2020, 15:54:33
s2: 10/05/2020, 15:54:33
Dolly Solanki  Dolly Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription