Python datetime

In this article, you will learn to manipulate date and time in Python with the help of examples.

Python has a module named datetime to work with dates and times. Let's create a few simple programs related to date and time before we dig deeper.

Example 1: Get Current Date and Time

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)

When you run the program, the output will be something like:

2018-12-19 09:26:03.478039

Here, we have imported datetime module using import datetime statement.

One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime object containing the current local date and time.

Example 2: Get Current Date


import datetime

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

When you run the program, the output will be something like:

In this program, 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 get a list containing all attributes of a module.

When you run the program, the output will be:

Commonly used classes in the datetime module are:

  • date Class

  • time Class

  • datetime Class

  • timedelta Class

datetime.date Class

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

Example 3: Date object to represent a date

When you run the program, the output will be:

If you are wondering, date() in the above example is a constructor of the date class. The constructor takes three arguments: year, month and day.

The variable a is a date object.

We can only import date class from the datetime module. Here's how:

Example 4: Get current date

You can create a date object containing the current date by using a classmethod named today(). Here's how:

Example 5: Get date from a timestamp

We can also create date objects from a timestamp. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC. You can convert a timestamp to date using fromtimestamp() method.

When you run the program, the output will be:

Example 6: Print today's year, month and day

We can get year, month, day, day of the week etc. from the date object easily. Here's how:

datetime.time

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

Example 7: Time object to represent time

When you run the program, the output will be:

Example 8: Print hour, minute, second and microsecond

Once you create a time object, you can easily print its attributes such as hour, minute etc.

When you run the example, the output will be:

Notice that we haven't passed microsecond argument. Hence, its default value 0 is printed.

datetime.datetime

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

Example 9: Python datetime object

When you run the program, the output will be:

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

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

When you run the program, the output will be:

datetime.timedelta

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

Example 11: Difference between two dates and times

When you run the program, the output will be:

Notice, both t3 and t6 are of <class 'datetime.timedelta'> type.

Example 12: Difference between two timedelta objects

When you run the program, the output will be:

Here, we have created two timedelta objects t1 and t2, and their difference is printed on the screen.

Example 13: Printing negative timedelta object

When you run the program, the output will be:

Example 14: Time duration in seconds

You can get the total number of seconds in a timedelta object using total_seconds() method.

When you run the program, the output will be:

You can also find sum of two dates and times using + operator. Also, you can multiply and divide a timedelta object by integers and floats.

Python format datetime

The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.

Python has strftime() and strptime() methods to handle this.

Python strftime() - datetime object to string

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

Example 15: Format date using strftime()

When you run the program, the output will be something like:

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

In the above program, t, s1 and s2 are strings.

  • %Y - year [0001,..., 2018, 2019,..., 9999]

  • %m - month [01, 02, ..., 11, 12]

  • %d - day [01, 02, ..., 30, 31]

  • %H - hour [00, 01, ..., 22, 23

  • %M - minute [00, 01, ..., 58, 59]

  • %S - second [00, 01, ..., 58, 59]

To learn more about strftime() and format codes, visit: Python strftime().

Python strptime() - string to datetime

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

Example 16: strptime()

When you run the program, the output will be:

The strptime() method takes two arguments:

  1. a string representing date and time

  2. format code equivalent to the first argument

By the way, %d, %B and %Y format codes are used for day, month(full name) and year respectively.

Visit Python strptime() to learn more.

Handling timezone in Python

Suppose, you are working on a project and need to display date and time based on their timezone. Rather than trying to handle timezone yourself, we suggest you to use a third-party pytZ module.

When you run the program, the output will be something like:

Here, datetime_NY and datetime_London are datetime objects containing the current date and time of their respective timezone.

Last updated

Was this helpful?