Python Datetime

Python has no date data type of it’s own, so we need to import a special library to introduce the date data type. This library is called the Python Datetime library.

You may also be interested in the time library. If you intend to be working in areas where time plays a major role, I recommend you read up on both these libraries and then make your decision, or maybe even use both at once.

Before we proceed any further, make sure you have the Python Datetime library installed!


Finding the Current time

import datetime

timestamp = datetime.datetime.now()
print(timestamp)

You can expect the output for this to resemble the format below.

# OUTPUT
2020-03-04 13:08:30.160118

As you can see, it’s alot of information. All the way from the year to microseconds being displayed. We don’t necessarily want to have all this display, or maybe just want to separate portions of it. To accomplish this, we can use the following keywords.

import datetime

timestamp = datetime.datetime.now()
print("Year: ",timestamp.year)
print("Month: ",timestamp.month)
print("Day: ", timestamp.day)
print("Hour: ",timestamp.hour)
print("Minute: ",timestamp.minute)
print("Second: ", timestamp.second)
print("Microsecond: ",timestamp.microsecond)
# OUTPUT
Year:  2020
Month:  3
Day:  4
Hour:  13
Minute:  14
Second:  55
Microsecond:  258183

The strftime() function

The output shown above is all in integers. But what if you wanted the Month February as a string “February” rather than a simple integer value 2 representing the second month.

This is where the strftime() function comes in. A little tip, think of it as the abbreviation for “string format time”. Because what it does is format time and return it as a string. It takes as input special codes as arugments that return a specific value.

import datetime
tstamp = datetime.datetime.now()
print(tstamp.strftime("%a"))
print(tstamp.strftime("%A"))
print(tstamp.strftime("%b"))
print(tstamp.strftime("%B"))

A complete list of all codes.

ArgumentDescriptionExample Output
%aWeekday – short formMon
%AWeekday – Full formMonday
%bMonth – Short formFeb
%BMonth – Full formFebruary
%yYear – Short form20
%YYear – Full form 2020
%wWeekday, 0 – 6 (0 is Sunday)2
%dDays in a month, 1 – 3117
%mNumerical Month, 1 – 128
%H24 Hour clock21
%I12 Hour clock9
%pAM/PMAM
%MMinutes, 0 – 5954
%SSeconds, 0 – 5923
%fMicroseconds, 0 – 999999104384
%zUTC offset+0500
%ZTime ZonePST
%jDay in a year, 1 – 366243
%cDate and time Fri Feb 13 11:31:04 2020
%xdate 11/7/20
%Xtime4:16:20

If you were in here simply for the basics, this point marks all that. This second half is going to get a bit more complicated with objects and whatnot.


Creating a Date Object

Sometimes we may want to be working with objects rather than numbers or strings. We can create a Datetime object by calling the class Datetime() and passing appropriate values into it’s parameters.

x = datetime.datetime(year, month, day, hour,
                      minute, second, microsecond, tzone)

Above is a demonstration of how to use the Datetime() class and a full list of all it’s parameters. Note though, only the first three are compulsory. The rest are optional.

Fun fact: The datetime module brings in several constants with it. The Maximum allowed value for year is 9999, and minimum is 1.

Working with Datetime Objects

You’ve learn how to deconstruct and construct them. Now it’s time to learn how to use them. When working with Dates, you’ll often find yourself trying to find the difference between the two dates. You can do it by one of two ways.

Either subtract each attribute individually as shown at the beginning of the article. For instance, for the difference in hours, object.hourobject2.hour. The catch here is that you would have to do this for each attribute to get the complete difference in date.

The second method directly handles this all for you. Just one simple subtraction is required.

import datetime

a = datetime.datetime(2021,3,20,12)
b = datetime.datetime(2020,4,11,8)
c = a - b

print("Days: ",c.days)
print("seconds: ",c.seconds)
Days:  343
seconds:  14400

This code may confuse some people. For one, why not print out the hours by using something like c.hours. The answer to this is that when two datetime objects go through such operations like addition and subtraction, instead of a python datetime object, a timedelta object is returned.

Keep in mind, that datetime objects can only be subtracted. Any attempt to add, multiple or divide will result in an error.

Python timedelta

The timedelta object only supports three time formats, object.days, object.seconds and object.microseconds.

Unlike datetime objects, timedelta objects can be added, multiplied, divided to both other timedelta objects and datetime objects.


This is as far as we’ll be covering here, for the sake of keeping things relevant and concise. For more information, here’s a link to the docs for the Datetime library.

Any suggestions or corrections are more than welcome. Any questions can be asked below in the comments. Anything to help improve our site, CodersLegacy is much appreciated.