Hi everyone, In this tutorial, we will learn how to format dates in Python with many examples using the built-in datetime module that provides classes to work with dates and time. We will learn how to convert objects of date, time, datetime into a string representation and a string into datetime object using strftime() and strptime() methods.

1. Date to String using strftime()

In this section, we will see how to convert the date, time, datetime objects into their string representation.

1.1- Time object to string using strftime()

Let’s import the datetime module and create an object of class time.

# importing datetime module
import datetime
# using time class from datetime module
# we create a time class object
ex_time = datetime.time(13,50,25,65800)
print(ex_time)
# printing the type of object
print(type(ex_time))

Output:

12:50:25.065800
<class 'datetime.time'>

The output is in format hours:minutes:seconds.microseconds. Let’s verify these by printing the attributes separately.

# Printing all attributes separately
print("Hour : ",ex_time.hour)
print("Minutes : ",ex_time.minute)
print("Seconds : ",ex_time.second)
print("Microseconds : ",ex_time.microsecond)

Output:

Hour : 13
Minutes : 50
Seconds : 25
Microseconds : 65800

Now we have a time object, its time to use strftime() method to convert it into a string. We will use some format codes to achieve all this. It is similar to how the string formatting is done. You can refer to this tutorial on string formatting to know more.

Refer to the link of Format Codes in the reference section at the end to know more about Format codes used in Date and Time formatting

  •  %H, %M, %S format codes

    • %H – Hour (24-hour clock) as a zero-padded decimal number.
    • %M – Minute as a zero-padded decimal number.
    • %S – Second as a zero-padded decimal number.
print(ex_time.strftime("%H-%M-%S"))

Output:

13-50-25
  •  %I, %f, %p format codes

    • %I – Hour (12-hour clock) as a zero-padded decimal number.
    • %f – Microsecond as a decimal number, zero-padded on the left.
    • %p – Locale’s equivalent of either AM or PM.
print(ex_time.strftime("%I:%M:%S.%f %p"))

Output:

01:50:25.065800 PM
Note – The type of all the outputs are string

1.2-  datetime object to string using strftime()

As we have done in the above section, in this section we will create an object of type datetime. Since format codes remain the same, By the end of this section, we will be able to format most of the dates and times.

ex_date = datetime.datetime(year=2020, month=11, day=10, hour=16, minute=38, second=40)
print(ex_date)
print(type(ex_date))

Output:

2020-11-10 16:38:40

<class 'datetime.datetime'>

We see that we have created a datetime object with defined date and time, let us see how to print the same date-time differently using other format codes.

  •  %d, %m, %Y format codes

    • %d – Day of the month as a zero-padded decimal number
    • %m – Month as a zero-padded decimal number.
    • %Y – Year with century as a decimal number.
print(ex_date.strftime("%d/%m/%Y %H-%M-%S"))

Output:

10/11/2020 16-38-40
  •  %a, %w, %y, %b format codes

    • %a – Weekday as locale’s abbreviated name.
    • %w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
    • %b – Month as locale’s abbreviated name.
    • %y – Year with century as a decimal number.
print(ex_date.strftime("%a %w %d-%b-%y %H-%M-%S"))

Output:

Tue 2 10-Nov-20 16-38-40
  •  %A, %B, %W format codes

    • %A – Weekday as locale’s full name.
    • %B – Month as locale’s full name.
    • %W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
print(ex_date.strftime("%A %W '%d %B %Y' %H-%M-%S %p"))

Output:

Tuesday 45 '10 November 2020' 16-38-40 PM

With these, we have finished the section and know how to convert a datetime object into a string representation using format codes. Let’s see how we can convert a string to a datetime object.

2. String to Date using strptime()

In this section, we will use the same format codes and a string to represent that string into a date-time representation. The strptime() method of datetime class from datetime module takes 2 parameters, a string of date and a format string in which we want to convert respectively. This format string is made up of the format codes that we have studied and any inappropriate conversion will lead to a value error.

2.1 converting a simple string into a date.

import datetime

date_string1 = "15/09/20"
print(datetime.datetime.strptime(date_string1,'%d/%m/%y'))

Output:

2020-09-15 00:00:00

2.2 converting a string containing date and time in random order

date_string2 = "Nov15202016-05-30"
print(datetime.datetime.strptime(date_string2,'%b%d%Y%H-%M-%S'))

Output:

2020-11-15 16:05:30

In this tutorial, we have how to format dates in Python. If you have any doubt, feel free to ask in the comment section.

References

Happy Learning 🙂

About the Author:

Aspiring Data Scientist who loves Python Programming, Software Development and wants to Solve Real-world Problems.

Leave A Comment