Python Datetime

In this tutorial, you will learn about Python's datatime module to work with date and time.

Depending on what purposes we're using Python for, we may want to deal with data containing dates and times.

In Python, we use the datetime module to work with dates and times.


Get Current Date in Python

In Python, we can find the current date using the today() function defined in the date class of the datetime module. For example,

# import datetime module
import datetime as dt

# use today() to get current date
current_date = dt.date.today()

print(current_date)

# Output: 2022-09-29

In the above example, we first imported the datetime module as dt. Notice the code,

dt.date.today() 

Here, we have used the today() method defined in the date class to find the current date.


Common Classes Used in Datetime Module

Some commonly used classes in the datetime module are:

  • date class - to work with date
  • time class - to work with time
  • datetime class - combination of date and time classes
  • timedelta class - to represent difference between two dates or times

The datetime.date Class in Python

In Python, the date class of the datetime module is used to create date objects that can store year, month, and day. For example,

import datetime as dt

date1 = dt.date(2022, 9, 29)
print(date1)

print('Year:', date1.year)
print('Month:', date1.month)
print('Day:', date1.day)

Output

2022-09-29
Year: 2022
Month: 9
Day: 29

In the above example, date() is a constructor of the date class. The constructor takes three arguments: year, month, and day.

We then used:

  • date1.year - to access year
  • date1.month - to access month
  • date1.day - to access day

The datetime.time Class in Python

The time class of the datetime module in Python is used to create time objects that can store time of day like hours, minutes, seconds, and microseconds.

The time class takes in all optional integer arguments. By default all of them are 0.

  1. The first argument is hour from 0 to 24.
  2. The second one is minutes from 0 to 60.
  3. The third is seconds from 0 to 60.
  4. The fourth is microsecond from 0 to 999999.

Let's see an example,

import datetime as dt

time1 = dt.time(9, 14, 47, 148659)
print(time1)

print('Hour:', time1.hour)
print('Minute:', time1.minute)
print('Second:', time1.second)
print('Microsecond:', time1.microsecond)

Output

09:14:47.148659
Hour: 9
Minute: 14
Second: 47
Microsecond: 148659

In the above example, time() is a constructor of the time class. The constructor here takes four arguments: hour, minute, second, and microsecond.

We then used

  • time1.hour - to access hour
  • time1.minute - to access minute
  • time1.second - to access second
  • time1.microsecond - to access microsecond

The datetime.datetime Class in Python

In Python, the datetime class of the datetime module is used to create objects that contain all the information from a date object as well as a time object.

import datetime as dt

datetime_obj = dt.datetime(2022, 9, 29, 10, 27, 48)

print(datetime_obj)

print(datetime_obj.date())
print(datetime_obj.time())

Output

2022-09-29 10:27:48
2022-09-29
10:27:48

In the above example, datetime() is a constructor of the datetime class. Notice the code,

  • datetime_obj - returns both date and time from datetime()
  • datetime_obj.date() - returns date from datetime()
  • datetime_obj.time() - returns time() from datetime()

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


Get Current Date and Time in Python

To find the current date and time in Python, we use the now() method defined in the datetime class of the datetime module. For example,

# import datetime module
import datetime as dt

# use now() to get current date and time
current_date_time = dt.datetime.now()

print(current_date_time)

# Output:  2022-09-29 03:37:25.345238

Here, we have used the now() method defined in the datetime class of the datetime module to find current date and time:

dt.datetime.now()

The datetime.timedelta Class in Python

In Python, we use the timedelta object to represent the difference between two dates or times. For example,

import datetime as dt

current_time = dt.datetime.now()
next_new_year = dt.datetime(2023, 1, 1)

time_remaining = next_new_year - current_time

print(time_remaining)
print(type(time_remaining))

Output

93 days, 20:21:00.793799
<class 'datetime.timedelta'>

Here, time_remaining stores the difference between next_new_year and current_time.

Notice that time_remaining is of the <class 'datetime.timedelta'> type.


Python strftime() method

The strftime() method returns a string representing date and time for the datetime object.

There are many formats to write the date and time depending on your location.

If you are in the US, you probably use the mm-dd-yyyy format while if you're in the UK you will generally use the dd-mm-yyyy format.

The strftime() method allows us to display the date and time in a custom specific format.

Let's see an example,

import datetime as dt

# current date and time
current_datetime = dt.datetime.now()

# H:M:S time format
time1 = current_datetime.strftime("%H:%M:%S") 
print('Time:', time1)

# mm/dd/YY H:M:S format
date_time1 = current_datetime.strftime("%m/%d/%Y, %H:%M:%S")
print('mm/dd/YY H:M:S Format :', date_time1)

# dd/mm/YY H:M:S format
date_time2 = current_datetime.strftime("%d/%m/%Y, %H:%M:%S")
print('dd/mm/YY H:M:S Format:', date_time2)

Output

Time: 03:46:18
mm/dd/YY H:M:S Format : 09/29/2022, 03:46:18
dd/mm/YY H:M:S Format: 29/09/2022, 03:46:18

In the above example, we have used the strftime() method and passed different format codes inside the method to return a formatted string based on it.

Here, the format codes

  1. %Y - represents year [from 0001 to 9999]
  2. %m - month [from 01 to 12]
  3. %d - day [form 01 to 31]
  4. %H - hour [from 00 to 23]
  5. %M - minute [from 00 to 59]
  6. %S - second [from 00 to 59]

Example: Python strftime() method

import datetime as dt

current_datetime = dt.datetime.now()
print(current_datetime)

string_date = current_datetime.strftime("%A, %B %d, %Y")
print(string_date)

Output

2022-09-29 03:49:22.866402
Thursday, September 29, 2022

Here,

  1. %A - represents the weekday name i.e. Thursday
  2. %B - represents the month's full name i.e. September
  3. %d - represents the day of the month i.e. 20
  4. %Y - represents the year i.e. 2022

Other Format Codes

Directive Meaning Example
%a Abbreviated weekday name Sun, Mon, ...
%A Full weekday name Sunday, Monday, ...
%w Weekday as a decimal number 0, 1, ..., 6
%d Day of the month as a zero-padded decimal 01, 02, ..., 31
%b Abbreviated month name Jan, Feb, ..., Dec
%p Locale's AM or PM

Python strptime() method

In Python, the strptime() method converts strings to datetime objects. For example,

import datetime as dt

date_string = "29 September, 2022"
print('String Date:', date_string)

date_object = dt.datetime.strptime(date_string, "%d %B, %Y")
print('String to datetime:', date_object)

Output

String Date: 29 September, 2022
String to datetime: 2022-09-29 00:00:00

In the above example, we have used the strptime() method to convert string date to datetime object.

strptime() takes two arguments:

  1. a string representing date and time
  2. format code equivalent to the first argument
Did you find this article helpful?