Menu Close

Python Datetime Module Tutorial

In this article, we are going to learn all about the Python DateTime module with the help of examples. Python DateTime module plays the most important role when you want to work with date time.

To understand this example you should have basic knowledge of Python Programming.

Python Datetime Module

In Python, DateTime is a built-in module that means you don’t need to install this module using pip.

Python DateTime module mainly deals with time and date. Python DateTime module provides various classes to work with data and time and that classes have various methods and deal with date and time.
DateTime module already installed in your system during python installation. you can directly import the Python DateTime module in your python program and work on it.

Constants

The datetime module provides following constants.

MINYEAR

The smallest year number allow in date or datetime object. MINYEAR is 1.

MAXYEAR

The largest year number allow in date or datetime object. MINYEAR is 9999.

Types

Python datetime module provides various types.

datetime.date

date() function returns the date object. Attributes of date method are year, month and day.

from datetime import date
x = date(year=2012, month=2, day=12)
print(x)
print(x.year)
print(x.month)
print(x.day)

datetime.time

time() function returns the time object. Attributes of date method are hour, minute, seconds, microsecond.

from datetime import time
t = time(12, 40, 50, 30)
print(t)

datetime.timedelta

This class is generally used for calculating differences in date, time or datetime instances.

from datetime import timedelta, datetime

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

#calculating future date and time for two years
future_date = current_date_time  + timedelta(days=720)
print(future_date)

datetime.datetime

To create a DateTime object we can use the DateTime class (constructor) of the DateTime module.
Parameters of DateTime class are year, month, day, hour, minutes, second, microsecond, tzinfo.

The datetime() class requires some parameters to create a DateTime: year, month, day, hour, minute, second, microsecond.

from datetime import datetime
t = datetime(2020, 2, 20, 12, 30, 20, 10)
print(t)

Current date and time

To display current date and time, we will use now() function that returns the current system date and time.

from datetime import datetime
result = datetime.now()
print(result)

#Display the current year, month, day, hour, month, seconds, and microsecond.

from datetime import datetime
result = datetime.now()
print(result)
print(result.year)
print(result.month)
print(result.day)
print(result.hour)
print(result.minute)
print(result.microsecond)

current UTC date and time

datetime.utcnow() method returns the current UTC date and time.

from datetime import datetime
result = datetime.utcnow()
print(result)

Get date from timestamp

Here we are going to create a date type object with the help of timestamp. A timestamp is a number of seconds between a particular date.

from datetime import date
result = date.fromtimestamp(1618677414)
print('Date is:- ', result)

Get date from isoformat

date.fromisoformat() method is returns the date from the date string.

from datetime import date
result = date.fromisoformat('2021-04-17')
print('Date is:- ', result)

Get date and time from timestamp

datetime.fromtimestamp() method returns the date and time from the timestamp.

from datetime import datetime
result = datetime.fromtimestamp(1618677414)
print('Date is:- ', result)

date.strftime()

date.strftime() is used to convert date object to string date according to given format.

from datetime import date
date_object = date.today()
print(date_object)
print('---------')
date_string = date.strftime(date_object, '%Y/%m/%d')
print(date_string)

datetime.strftime() method

datetime.strftime() method is used to convert the datetime object to string based on given format.

from datetime import datetime
datetime_object = datetime.now()
print('Date and Time is (Datetime object type):- ', datetime_object)

date_string = datetime.strftime(datetime_object, '%Y-%m-%d %H:%M:%S.%f')
print('Date and Time is (String type):- ', date_string)

datetime.strptime() method

datetime.strptime() method is used to convert string date and time into datetime object.

from datetime import datetime
string_datetime = '2021-04-17 22:43:47.731291'
print(string_datetime)
print(type(string_datetime))

print('---------')
datetme_object = datetime.strptime(string_datetime,  '%Y-%m-%d %H:%M:%S.%f')
print(datetme_object)
print(type(datetme_object))

strftime() and strptime() format code

All the format reference of strftime() and strptime() method:

DirectiveDescriptionExample
%aWeekday, short versionWed
%AWeekday, full versionWednesday
%dDay of month 01-3131
%wWeekday as a number 0-6, 0 is Sunday3
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mYear, short version, without century18
%YYear, full version2018
%HHour 00-2317
%IHour 00-1205
%pAM/PMPM
%MMinute 00-5941
%SSecond 00-5908
%fMicrosecond 000000-999999548513
%zUTC offset+0100
%ZTimezoneCST
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week00-53 52
%WWeek number of year, Monday as the first day of week00-53 52
%cThe local version of the date and timeMon Dec 31 17:41:00 2018
%xThe local version of the date12/31/18
%XThe local version of time17:41:00

To get the all the attributes of datetime module, you have to use dir() function.

import datetime
result = dir(datetime)
print(result)

datetime to timestamp

datetime.timestamp() method is used to convert datetime to timestamp.

from datetime import datetime
datetime_string = '2021-04-17 22:43:47'
datetime_object = datetime.strptime(datetime_string, '%Y-%m-%d %H:%M:%S')
print(datetime.timestamp(datetime_object))

Date to timestamp

Convert date to timestamp using timestamp() function.

from datetime import datetime
date_string = '2021-04-17'
date_object = datetime.strptime(date_string, '%Y-%m-%d')
print(datetime.timestamp(date_object))

Conclusion

In this Python DateTime module tutorial, we have seen all about the python DateTime module along with examples. I am sure, you don’t have any confusion regarding the python DateTime module.

If you want to work with date and time in your Python project, Then this module is going to helpful for you, with the halp of datetime module you can perform any type of operations on date and time.

If you like this article, please share and keep visiting for out further Python tutorials.

Reference:- Click Here

Python Math Module
Python Time Module Tutorial

Related Posts