Python datetime to String


In this article, you will learn how to convert datetime to string in Python. You will understand the need for conversion and everything around it.

In python, datetime is an object (returned by datetime module) that represents a date and time. It stores information like year, month, day, hour, minute, second, microsecond, and timezone.

The informations are extracted from the datetime object using the strftime() method of the datetime object.

When printed the datetime object, it returns a string in the format YYYY-MM-DD HH:MM:SS.mmmmmm and has the type of <class 'datetime.datetime'>.

python datetime to string

Let's look at how we can extract different informations from a given datetime object and display it in different string formats.


Using strftime() method

strftime() is a method of datetime class in datetime module. It is used to convert datetime object to string.

strftime Method
strftime() Method

To use strftime() method, you need to import datetime module.

It accepts a format string as an argument and returns a string representing the date and time using that format.

Example:

Example
import datetime as dt

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

# convert to string
now_string = now.strftime("%d/%m/%Y %H:%M:%S")

print(now_string)
Output: 01/01/2021 00:00:00

Here is another example to show the date in format January 1, 2021.

Example
import datetime as dt

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

# convert to string
now_string = now.strftime("%B %d, %Y")

print(now_string)
Output: January 01, 2021

Characters used in the above code like %A, %B, %d, %Y are called format directives. They are used to represent different parts of date and time.


Format Directives

Format directives are codes that are used to represent different parts of datetime object.

It is represented by a % sign followed by a character. The character represents the part of the date and time that you want to express.

Here is the list of all the format directives that can be used with strftime() method.

DirectiveDescriptionExample
%aAbbreviated weekday nameSun, Mon, ..., Sat
%AFull weekday nameSunday, Monday, ..., Saturday
%bAbbreviated month nameJan, Feb, ..., Dec
%BFull month nameJanuary, February, ..., December
%cLocale's date and time representationTue Mar 27 11:45:40 2018
%dDay of the month as a zero-padded decimal number01, 02, ..., 31
%HHour (24-hour clock) as a zero-padded decimal number00, 01, ..., 23
%IHour (12-hour clock) as a zero-padded decimal number01, 02, ..., 12
%jDay of the year as a zero-padded decimal number001, 002, ..., 366
%mMonth as a zero-padded decimal number01, 02, ..., 12
%MMinute as a zero-padded decimal number00, 01, ..., 59
%pLocale's equivalent of AM or PMAM, PM
%SSecond as a zero-padded decimal number00, 01, ..., 59
%UWeek number of the year (Sunday as the first day of the week) as a zero-padded decimal number00, 01, ..., 53
%wWeekday as a decimal number (0 is Sunday)0, 1, ..., 6
%WWeek number of the year (Monday as the first day of the week) as a zero-padded decimal number00, 01, ..., 53
%xLocale's date representation03/27/18
%XLocale's time representation10:24:55
%yYear without century as a zero-padded decimal number00, 01, ..., 99
%YYear with century as a decimal number0001, 0002, ..., 2018, 2019, ..., 9998, 9999
%zUTC offset in the form +HHMM or -HHMM+0000, -0400, +1030
%ZTime zone name (empty string if the object is naive)(empty), UTC, EST, CST
%%A literal '%' character%

Here is an example that shows individual components of a datetime object.

Example
import datetime as dt

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

# individual components
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second

print("Year: ", year)
print("Month: ", month)
print("Day: ", day)
print("Hour: ", hour)
print("Minute: ", minute)
print("Second: ", second)
Output:
Year:  2018
Month:  3
Day:  27
Hour:  10
Minute:  24
Second:  55

Example: Python datetime to string format

Let's see different kinds of examples to convert datetime to string format.

Example 1

Converting datetime object to string in YYYY-MM-DD format.

Example
import datetime as dt

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

# format: YYYY-MM-DD
now_string = now.strftime("%Y-%m-%d")

print(now_string)
Output: 2018-03-27

Example 2

Converting datetime object to string in YYYY-MM-DD HH:MM:SS format.

Example
import datetime as dt

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

# format: YYYY-MM-DD HH:MM:SS
now_string = now.strftime("%Y-%m-%d %H:%M:%S")

print(now_string)
Output: 2018-03-27 10:24:55

Example 3

Converting datetime object to string in Month DD, YYYY format.

Example
import datetime as dt

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

# format: Month DD, YYYY
now_string = now.strftime("%B %d, %Y")

print(now_string)
Output: March 27, 2018

Example 4

Converting datetime object to string in Month DD, YYYY HH:MM:SS format.

Example
import datetime as dt

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

# format: Month DD, YYYY HH:MM:SS
now_string = now.strftime("%B %d, %Y %H:%M:%S")

print(now_string)
Output: March 27, 2018 10:24:55

Example 5

Converting datetime object to string in DD/MM/YYYY format.

Example
import datetime as dt

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

# format: DD/MM/YYYY
now_string = now.strftime("%d/%m/%Y")

print(now_string)
Output: 27/03/2018

Bonus💰: Timestamp to String Python

Above we have converted datetime object to string. But what if we have a timestamp instead of datetime object?🤔

We can convert timestamp to datetime object and then convert datetime object to string using strftime() method.

Let's see an example.

Example
import datetime as dt

# timestamp
timestamp = 1222098295

# convert timestamp to datetime object
dt_object = dt.datetime.fromtimestamp(timestamp)

# format: Month DD, YYYY HH:MM:SS
now_string = dt_object.strftime("%B %d, %Y %H:%M:%S")

print(now_string)
Output: September 22, 2008 21:14:55

Conclusion

So, this was all about converting datetime objects to strings in Python. You have gone through multiple examples.

By understanding the concept now you can convert datetime objects and timestamp to strings in any format you want.

Happy Learning!😊