Python datetime module



Python offers a module named datetime to work with dates and times. Let us create different simple programs related to date and time before going dip.


Get Current Date and Time

import datetime

datetime_obj = datetime.datetime.now()
print(datetime_obj)

After running the above program, the output will be as follows:

2017-10-27 04:45:18.213510

Above, we imported the datetime module using import module statement.

Inside the datetime module, there is a datetime class. We called now() method to create a datetime object which contains the current local date and time.


Get Current Date

import datetime

date_obj = datetime.date.today()
print(date_obj)

After running the above program, the output will be as follows:

2017-10-27

Above, we have used today() method defined in the date class to get a date object containing the current local date.


What's inside datetime?

We can use dir() function to list all attributes of a module.

import datetime

print(dir(datetime))

The output of the above code will be as follows:

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

The most used classes in the datetime module are:

  • date Class
  • time Class
  • datetime Class
  • timedelta Class

datetime.date Class

We can instantiate date object from the date class. A date object represents a date (year, month, and day)


Example: Date object to represent a date

import datetime

d = datetime.date(2017, 3, 16)
print(d)

After running the above program, the output will be as follows:

2017-03-16

The date() in the above code is a constructor of the date class. The constructor accepts three arguments: year, month and day.

The variable d is a date object.


To only import date class from the datetime module, we can write the following code:

from datetime import date

d = datetime.date(2017, 3, 16)
print(d)

Example: Get current date

We can create a date object containing the current date using a classmethod named today().

from datetime import date

today = date.today()
print("Current date: ", today)

Output

Current date:  2017-10-27

Example: Get date from a timestamp

Python makes it also possible to create date objects from a timestamp. A Unix timestamp is the number of seconds between a given date and January 1, 1970 at UTC. We can convert a timestamp to date using fromtimestamp method.

from datetime import date

timestamp = date.fromtimestamp(985454597)
print("Date =", timestamp)

After running the program, the output will be:

Date = 2001-03-24

Example: Print today's year, month and day

We can get a year, month, day day of the week from the date object as follows:

from datetime import date

today = date.today()

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

Output

Current year: 2017 
Current month: 10 
Current day: 27

datetime.time

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


Exmaple: Time object to represent time

from datetime import time

a = time()
print("a =", a)

b = time(10, 30, 40)
print("b =", b)

c = time(hour = 10, minute = 30, second = 40)
print("c =", c)

d = time(10, 30, 40, 12124)
print("d =", d)

The output of the above program will be:

a = 00:00:00 
b = 10:30:40 
c = 10:30:40 
d = 10:30:40.012124

Example: Print hour, minute, second and microsecond

After creating a time object, we can easily print its attributes such as hour, minute etc.

from datetime import time

x = time(10, 30, 40)

print("hour =", x.hour)
print("minute =", x.minute)
print("second =", x.second)
print("microsecond =", x.microsecond)

The output of the above code will be as follows:

hour = 10 
minute = 30 
second = 40 
microsecond = 12124

The default value of the microsecond argument is 0.


datetime.datetime

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


Example: Python datetime object

from datetime import datetime

# datetime(year, month, day)
x = datetime(2017, 10, 27)
print(x)

# datetime(year, month, day, hour, minute, second, microsecond)
y = datetime(2017, 10, 27, 10, 30, 40, 45455)
print(y)

After executing the above program, the output will be:

2017-10-27 00:00:00 
2017-10-27 10:30:40.045455

The first three arguments year, month and day of the datetime() constructor are mandatory.


Example: Print year, month, hour, minute and timestamp

from datetime import datetime

x = datetime(2017, 10, 27, 10, 30, 40, 45455)

print("year =", x.year)
print("month =", x.month)
print("hour =", x.hour)
print("minute =", x.minute)
print("timestamp =", x.timestamp())

The output of the above program will be as follows:

year = 2017 
month = 10 
hour = 10 
minute = 30 
timestamp = 1509100240.045455

datetime.timedelta

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


Example: Difference between two dates and times

from datetime import datetime, date

t1 = date(year = 2019, month = 6, day = 14)
t2 = date(year = 2018, month = 3, day = 10)
t3 = t1 - t2
print("t3 =", t3)

t4 = datetime(year = 2016, month = 6, day = 14, hour = 8, minute= 23, second= 35)
t5 = datetime(year = 2017, month = 3, day = 10, hour = 4, minute = 28, second = 40)
t6 = t4 - t5
print("t6 =", t6)

print("type of t3 =", type(t3))
print("type of t6 =", type(t6))

After executing the above program, the output will be as follows:

t3 = 461 days, 0:00:00
t6 = -269 days, 3:54:55
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>

As we can see, both t3 and t6 are of <class 'datetime.timedelta'> type.


Python format datetime

The representation of date and time may be different in different countries, organizations, etc. In the US is more common to use mm/dd/yyyy, whereas dd/mm/yyyy is more common in France and UK.

Python offers strftime() and strptime() methods to hand this.


Python strftime() - datetime object to string

The strftime() method is defined under classes date, datetime and time. This method creates a formatted string from a given date, datetime or time object.


Example: Format date using strftime()

from datetime import datetime

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

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

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

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

After running the above program, the output will be as follows:

time: 08:00:17 
d1: 10/27/2017, 08:00:17 
d2: 27/10/2017, 08:0017

Above, %Y, %m, %d, %H, %M, %S are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.

Let us see the interval of every format codes:

  • %Y - year [0001, ...., 2017,2018,...., 9999]
  • %m - month [01, 02, .., 11, 12]
  • %d - date [01, 02, .., 30, 31]
  • %H - hour [00, 01, .., 22, 23]
  • %M - minute [00, 01, ..., 58, 59]
  • %S - second [00, 01, .., 58, 59]

Python strptime() - string to datetime

The sprtime() method creates a datetime object from a given string representing date and time.


Example: strptime()

from datetime import datetime

date_str = "26 July, 2017"
print("date_str =", date_str)

date_obj = datetime.strptime(date_str, "%d %B, %Y")
print("date_obj =", date_obj)

After executing the above program, the output will be as follows:

date_str = 26 July, 2017
date_obj = 2017-07-26 00:00:00

The strptime() method takes two arguments:

  • a string representing date and time
  • format code equivalent to the first argument

The format codes %d, %B and %Y are used for day, month (full name) and year, sequentially.


Handling timezone in Python

Let us assume, We are working on a project and need to display date and time based on their timezone. The best way to handle timezone is to use a third-party pytz module.

from datetime import datetime
import pytz

local = datetime.now()
print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S"))

tz_NY = pytz.timezone("America/New_York")
datetime_NY = datetime.now(tz_NY)
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))

tz_Paris = pytz.timezone("Europe/France")
datetime_Paris = datetime.now(tz_Paris)
print("Paris:", datetime_Paris.strftime("%m/%d/%Y, %H:%M:%S"))

The output of the above program will be as follows:

Local: 10/27/2018, 08:38:12 
NY: 10/27/2018, 04:38:12 
Paris: 10/27/2018, 10:38:12

The above, datetime_NY and datetime_Paris are datetime objects containing the current date and time of their respective timezone.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.