Python Datetime Module – Python Tutorial

Welcome back, everyone. In this lecture, we’re going to give you a brief tour of the Python DateTime module, which essentially allows you to create objects that have information not just on the date or the time, but also things like time zone and operations between DateTime objects, such as how many seconds have passed or how many days have passed.

Python datetime Module

Python has the DateTime module to help deal with timestamps in your code. Time values are represented with the time class. Times have attributes for an hour, minute, second, and microsecond. They can also include time zone information. The arguments to initialize a time instance are optional, but the default of 0 is unlikely to be what you want.

time

Let’s take a look at how we can extract time information from the DateTime module. We can create a timestamp by specifying DateTime.time(hour,minute,second,microsecond)

import datetime

t = datetime.time(4, 20, 1)

# Let's show the different components
print(t)
print('hour  :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo)

Output:

04:20:01
hour  : 4
minute: 20
second: 1
microsecond: 0
tzinfo: None
Note: A time instance only holds values of the time, and not the date associated with the time.

You can also check the min and max values a time of day which can have in the module:

print('The Earliest  :', datetime.time.min)
print('The Latest    :', datetime.time.max)
print('The Resolution:', datetime.time.resolution)
Output:
The Earliest  : 00:00:00
The Latest    : 23:59:59.999999
The Resolution: 0:00:00.000001

Note: The min and max class attributes of the Python datetime module reflect the valid range of times in a single day.

Date Object

datetime (as you might suspect) also allows us to work with date timestamps. Calendar date values are represented with the date class. Instances have attributes for year, month, and day. It is easy to create a date representing today’s date using the today() class method.

Let’s see some examples:


today = datetime.date.today()
print(today)
print('ctime:', today.ctime())
print('tuple:', today.timetuple())
print('ordinal:', today.toordinal())
print('Year :', today.year)
print('Month:', today.month)
print('Day  :', today.day)
2020-06-10
ctime: Wed Jun 10 00:00:00 2020
tuple: time.struct_time(tm_year=2020, tm_mon=6, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=162, tm_isdst=-1)
ordinal: 737586
Year : 2020
Month: 6
Day  : 10

As with time, the range of date values supported can be determined using the min and max attributes.

print('Earliest  :', datetime.date.min)
print('Latest    :', datetime.date.max)
print('Resolution:', datetime.date.resolution)

Output:

Earliest  : 0001-01-01
Latest    : 9999-12-31
Resolution: 1 day, 0:00:00

Another way to create new date instances uses the replace() method of the existing date. For example, you can change the year, leaving the day and month alone.

d1 = datetime.date(2015, 3, 11)
print('d1:', d1)

d2 = d1.replace(year=1990)
print('d2:', d2)

Output:

d1: 2015-03-11
d2: 1990-03-11

Arithmetic

We can perform arithmetic on date objects to check for time differences. For example:

Input:d1
Output: datetime.date(2015, 3, 11)
Input: d2 
Output: datetime.date(1990, 3, 11)
Input: d1-d2 
output: datetime.timedelta(9131)

This gives us the difference in days between the two dates. You can use the timedelta method to specify various units of times (days, minutes, hours, etc.)

What is timedelta method?

The timedelta object of python refers to the difference between two dates or times.

For example:

from datetime import datetime, date

a1 = date(year = 2018, month = 7, day = 12)
a2 = date(year = 2017, month = 12, day = 23)
a3 = a1 - a2
print("a3 =", a3)
OutPut will be:
python datetime module

Example of Python Datetime Module: Get Current Date and Time

To do that, I’m going to first say import Datetime module. And then we’re going to create a datetime object.

import datetime
mytime = datetime.datetime.now()
print(mytime)

Output:

python datetime module

So, above code will be return current date and timestamp.

Example 2: Get Current Date

import datetime

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

Output:

python datetime module

What is date.isocalendar()?

The date.isocalendar() returns a named tuple object with three components: yearweek and weekday.

What is date.timetuple()?

This returns a time.struct_time.

What is datetime.tzinfo?

The object passed as the tzinfo argument to the datetime constructor, or None if none was passed.

Must Read:

Great! You should now have a basic understanding of how to use the Python DateTime module with Python to work with timestamps in your code!

Leave a Reply

Your email address will not be published. Required fields are marked *