Python Datetime Module with Quick Examples


1. Python Datetime Module

With the ever-complex lifestyle we have adopted, date and time are extremely important. It is like we’re all slaves to time. In this tutorial, we will see how to work with Python Datetime Module.

Before we begin, you should refer to Python Date and Time.

2. The Datetime Module

Python Datetime Module Overview

Introduction to Python Datetime Module

The datetime module offers functions and classes for working with date and time parsing, formatting, and arithmetic. Lets start with Python Date time with Examples.

Two kinds of date and time objects exist- naïve and aware.

A naïve object is easier to deal with, and doesn’t have enough information to unambiguously locate itself relative to other date/time objects. An aware object is more realistic, it knows applicable algorithmic and political time adjustments.

To use this module, we must first import it.

>>> import datetime

It has the following constants:

a. MAXYEAR

MAXYEAR tells us the maximum value a year can take, which is 9999.

>>> datetime.MAXYEAR

9999

b. MINYEAR

The minimum value of year is 1. This is what MINYEAR returns.

>>> datetime.MINYEAR

1

Both MAXYEAR and MINYEAR are of the type integer.

>>> type(datetime.MAXYEAR),type(datetime.MINYEAR)

(<class ‘int’>, <class ‘int’>)

Bonus- type() is of the type type.

>>> type(type)

<class ‘type’>

Other than these constants, datetime has these datetime class types:

  1. class datetime.date

Python date is an idealized naïve date considering the current Gregorian calendar.

Attributes: year, month, and day.

  1. class datetime.time

Python time is an idealized time, independent of any particular day. Here, we assume that each day is made of exactly 24*60*60 seconds (no leap seconds).

Attributes: hour, minute, second, microsecond, and tzinfo.

  1. class datetime.datetime

When you combine a date and a time, you get a datetime.

>>> issubclass(datetime.datetime,datetime.date)

True

>>> issubclass(datetime.datetime,datetime.time)

False

Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.

  1. class datetime.timedelta

A timedelta is a duration expressing the difference between two date, time, or datetime instances to microsecond resolution.

  1. class datetime.tzinfo

tzinfo is an abstract base class we use for time zone information objects. The date and time classes use it to provide a customizable notion of time adjustment (for example, to account for time zone and/or DST(daylight saving time)).

  1. class datetime.timezone

timezone implements the tzinfo abstract base class as a fixed offset from the UTC.

Such objects are immutable. Also, objects of the type ‘date’ is naïve, but those of the types ‘time’ or ‘datetime’ may be aware or naïve. The next in Python Datetime Module Tutorial is Date Objects

3. date Objects

A date object represents a date with year, month, and day, according to the ideal Gregorian calendar.

With a date object, we have the following methods:

a. date(year, month, day)

This method will create an object of type ‘date’.

>>> d=datetime.date(2018,2,28)

Here, year can be from MAXYEAR to MINYEAR, and month can be from 1 to 12. The day can be from 1 to the number of days in the given month for the given year.

b. today()

today() will return the current local date.

>>> datetime.date.today()

datetime.date(2018, 2, 28)

c. fromtimestamp(timestamp)

fromtimestamp will return the date for the Python timestamp provided.

>>> import time
>>> time.time()

1519818814.358453

>>> datetime.date.fromtimestamp(time.time())

datetime.date(2018, 2, 28)

>>> datetime.date.fromtimestamp(time.time()+999999)

datetime.date(2018, 3, 12)

The date class also has these attributes:

a. date.min

It returns the earliest representable date.

>>> datetime.date.min

datetime.date(1, 1, 1)

b. date.max

Like min, max returns the latest representable date.

>>> datetime.date.max

datetime.date(9999, 12, 31)

c. date.resolution

resolution returns the smallest possible difference between non-equal date objects.

>>> datetime.date.resolution

datetime.timedelta(1)

We also have the following instance attributes:

a. year

This returns the year from a date object.

>>> d=datetime.date(2018,2,28)
>>> d.year

2018

b. month

month returns the month from a date object.

>>> d.month

2

c. day

This returns the day from a date object.

>>> d.day

28

And then, we have the following instance methods:

a. replace(year, month, day)

This will let us update any or all of these three values.

>>> d=d.replace(month=3,day=1)

datetime.date(2018, 3, 1)

b. timetuple()

timetuple() returns a tuple of attributes for the current local time.

>>> d.timetuple()

time.struct_time(tm_year=2018, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=59, tm_isdst=-1)

c. weekday()

weekday() will return the day of the week, where 0 denotes Monday.

>>> d.weekday()

2

d. isoweekday()

Here, Monday is 1.

>>> d.isoweekday()

3

e. isocalendar()

This method returns a tuple of three things- ISO year, ISO week number, and ISO weekday.

>>> d.isocalendar()

(2018, 9, 3)

f. isoformat()

This returns the date in the ISO format.

>>> d.isoformat()

‘2018-02-28’

g. __str__()

This will return the current local date as a string.

>>> d.__str__()

‘2018-02-28’

>>> str(d)

‘2018-02-28’

h. ctime()

ctime returns the current local date in a string format.

>>> d.ctime()

‘Wed Feb 28 00:00:00 2018’

We can also perform some operations on a date object:

>>> d=datetime.date(2018,12,30)
>>> td=datetime.timedelta(0,99999)
>>> d1=d+td
>>> d1

datetime.date(2018, 12, 31)

>>> d1<d

False

Any doubt yet in Date time module in Python or Examples? Please comment.

The Next in Python Datetime Module Tutorial is Time Objects

4. time Objects

A time object represents a local time of day. Its arguments are- hour, minute, second, microsecond, and tzinfo.

>>> t=datetime.time(11,59,59,99999)

The class time has the following attributes:

a. min

This returns the earliest representable time.

>>> t.min

datetime.time(0, 0)

b. max

This returns the latest representable time.

>>> t.max

datetime.time(23, 59, 59, 999999)

c. resolution

resolution returns the smallest possible difference between non-equal time objects.

>>> t.resolution

datetime.timedelta(0, 0, 1)

Now, let’s look at some non-readable instance attributes:

a. hour

This tells us the hour from the object.

>>> t.hour

11

b. minute

This returns the minute.

>>> t.minute

59

c. second

This returns the second.

>>> t.second

59

d. microsecond

This returns the microsecond.

>>> t.microsecond

99999

e. tzinfo

This returns whatever we pass as tzinfo to the object while creating it. If we didn’t, it returns None.

>>> print(t.tzinfo)

None

f. fold

This disambiguates wall times during a repeated interval.

>>> t.fold

0

We have the following instance methods:

a. replace()

This does the same as for ‘date’ objects.

>>> t=t.replace(hour=22,second=7)

b. isoformat()

This method returns the time in the object in the ISO format.

>>> t.isoformat()

’22:59:07.099999′

c. __str__()

This does the same as it does for ‘date’ objects.

>>> t.__str__()

’22:59:07.099999′

Now in the Python Datetime Module Tutorial Lets move ahead with datetime Objects

5. datetime Objects

A datetime objects knows about the date and the time. Arguments include year, month, day, hour, minute, second, microsecond, tzinfo.

>>> d=datetime.datetime(1995,12,31,10,0)

We have the following methods:

a. today()

This method returns the current local datetime.

>>> datetime.datetime.today()

datetime.datetime(2018, 2, 28, 19, 9, 40, 751445)

b. now()

now() returns the current local date and time, but is more precise than today().

>>> datetime.datetime.now()

datetime.datetime(2018, 2, 28, 19, 12, 45, 710542)

c. utcnow()

utcnow() returns the current UTC time.

>>> datetime.datetime.utcnow()

datetime.datetime(2018, 2, 28, 13, 49, 14, 486367)

d. fromtimestamp()

This returns the date and time for the provided timestamp.

>>> datetime.datetime.fromtimestamp(time.time())

datetime.datetime(2018, 2, 28, 19, 20, 24, 55451)

e. utctimestamp()

This is like the previous one, but it returns the UTC time.

>>> datetime.datetime.utcfromtimestamp(time.time())

datetime.datetime(2018, 2, 28, 13, 51, 56, 615793)

Now, let’s look at the class attributes:

a. min

Like for everything else, this returns the earliest representable datetime.

>>> datetime.datetime.min

datetime.datetime(1, 1, 1, 0, 0)

b. max

max returns the latest representable datetime.

>>> datetime.datetime.max

datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

c. resolution

Resolution is about the smallest possible difference between non-equal datetime objects.

>>> datetime.datetime.resolution

datetime.timedelta(0, 0, 1)

Now, let’s see some read-only instance attributes:

a. year

This returns the year.

>>> d.year

1995

b. month

This returns the month.

>>> d.month

12

c. day

This returns the day.

>>> d.day

31

d. hour

This returns the hour.

>>> d.hour

10

e. minute

This returns the minute.

>>> d.minute

0

f. second

This returns the second.

>>> d.second

0

g. microsecond

This returns the microsecond.

>>> d.microsecond

0

h. tzinfo

This returns the tzinfo; None, if we passed none while creating the object.

>>> print(d.tzinfo)

None

i. fold

This is the same as we discussed before.

>>> d.fold

0

Finally, let’s try some instance methods.

a. replace()

Again, this is like we have been doing so far.

>>> d.replace(microsecond=7)

datetime.datetime(1995, 12, 31, 10, 0, 0, 7)

b. date()

date() returns a date object from the datetime object.

>>> d.date()

datetime.date(1995, 12, 31)

c. time()

time() returns a time object from the datetime object.

>>> d.time()

datetime.time(10, 0)

d. timetz()

Other than what time() does, timetz() also returns the tzinfo value.

>>> d.timetz()

datetime.time(10, 0)

e. astimezone()

This returns a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time.

>>> d.astimezone()

datetime.datetime(1995, 12, 31, 10, 0, tzinfo=datetime.timezone(datetime.timedelta(0, 19800), ‘India Standard Time’))

f. utcoffset()

If there is a UTC offset, it returns that, else, None.

>>> print(d.utcoffset())

None

g. dst()

If Daylight Savings Time applies, it returns its magnitude.

>>> print(d.dst())

None

h. tzname

If you would have set tzinfo, this would return its name.

>>> print(d.tzname())

None

i. timetuple()

Like we saw earlier, this returns a time tuple of the object.

>>> d.timetuple()

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=-1)

j. utctimetuple()

This returns a time tuple of the UTC time.

>>> d.utctimetuple()

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=0)

k. timestamp()

This returns the timestamp of the object (in seconds).

>>> d.timestamp()

820384200.0

l. weekday()

This returns the number of weekday for the object, where 0 is for Monday.

>>> d.weekday()

6

#A Sunday

m. isoweekday()

This returns the day of the week, but with Monday as 1.

>>> d.isoweekday()

7

n. isocalendar()

This returns a tuple of the following- ISO year, ISO week number, ISO weekday.

>>> d.isocalendar()

(1995, 52, 7)

o. isoformat()

This returns the date and time in the ISO format.

>>> d.isoformat()

‘1995-12-31T10:00:00’

p. __str__()

This returns the date and time in a string representation.

>>> d.__str__()

‘1995-12-31 10:00:00’

>>> str(d)

‘1995-12-31 10:00:00’

q. ctime()

This, like str, returns the datetime as a string.

>>> d.ctime()

‘Sun Dec 31 10:00:00 1995’

Some operations that we can perform on a datetime object are:

>>> d=datetime.datetime(2018,12,30)
>>> td=datetime.timedelta(0,99999)
>>> d1=d+td
>>> d1

datetime.datetime(2018, 12, 31, 3, 46, 39)

>>> d<d1

True

6. timedelta Objects

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

Attributes: days, seconds, microseconds, milliseconds, minutes, hours, weeks

Here, seconds can be from 0 to 86399.

>>> td=datetime.timedelta(9,3,9999,999,58,22,3)

These attributes belong to the timedelta class:

a. min

This returns the most negative timedelta object.

>>> datetime.timedelta.min

datetime.timedelta(-999999999)

b. max

This one returns the most positive timedelta object.

>>> datetime.timedelta.max

datetime.timedelta(999999999, 86399, 999999)

c. resolution

resolution returns the smallest possible difference between non-equal timedelta objects.

>>> datetime.timedelta.resolution

datetime.timedelta(0, 0, 1)

timedelta also supports one instance method:

a. total_seconds()

This returns the total number of seconds in the duration.

>>> td.total_seconds()

2674684.008999

You can perform arithmetic operations on timedelta objects.

>>> td=datetime.timedelta(0,333)
>>> td1=td*2
>>> td1

datetime.timedelta(0, 666)

This was All about the Python Datetime Module Tutorial.

7. Conclusion: Python Datetime Module Tutorial

We hope that after this article on Python datetime Module Tutorial, and after Date and Time, you will be able to handle all date and time easily. If you think this is a bit too much for once, don’t panic. Work on it twice or thrice. Practice will do it for you. And comment if you need any help on Python Datetime examples.

Leave a comment

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