Python Datetime to String

Python Datetime to String

You can convert most of the objects to String using str() built-in method.

In this tutorial, we will convert Python Datetime object to String using str() built-in function and datetime.datetime.strftime() method.

The syntax of str() that we shall use is shown below

datetimeString = str(datetimeObject)

The syntax of strftime() is shown below

datetimeString = datetimeObject.strftime(format_string)
Run this program ONLINE

Examples for both of these scenarios are provided.

Example 1: Convert Datetime to String

In this example, we will get the current time using datetime.now(). datetime.now() returns object of class type datetime.datetime. We shall convert the datetime object to string using str(). And print the string and its type to console, just to make sure.

Python Program

import datetime

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

#convert date and time to string
dateTimeStr = str(x)

#print the date and time string
print(dateTimeStr)

#print the type of dateTimeStr
print(type(dateTimeStr))
Run this program ONLINE

Output

2019-12-10 05:19:10.982569
<class 'str'>

We have converted the datetime object to string.

Now, you can apply any string operations on this string. In the following program. let us get the date from datetime string using index slicing.

Python Program

import datetime

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

#convert date and time to string
dateTimeStr = str(x)

#just the date
print(dateTimeStr[:10])
Run this program ONLINE

Output

2019-12-10
Run this program ONLINE

Explanation

When you apply str(datetimeObject), internally datetime.__str__ () method is called. And calling str(datetimeObject) is equivalent to datetimeObject.isoformat(‘ ‘).

In the following example, we shall initialize a datetime object and check the results when we convert it to a string and also when print with isoformat(‘ ‘).

Python Program

import datetime

x = datetime.datetime(2020, 1, 1, 12, 30, 59, 0)

#convert the datetime object to string
datetimeStr = str(x)
print(datetimeStr)

#print the iso format of datetime object
print(x.isoformat(' '))
Run this program ONLINE

Output

2020-01-01 12:30:59
2020-01-01 12:30:59

Format Datetime String

You can also control the result when you convert datetime object to string using strftime() method.

strftime() accepts a format string, and returns the datetime formatted to this format.

Python Program

import datetime

x = datetime.datetime(2020, 1, 1, 12, 30, 59, 0)

#convert the datetime object to string of specific format
datetimeStr = x.strftime("%Y %B, %A %w, %H hours %M minutes")
print(datetimeStr)
Run this program ONLINE

Output

2020 January, Wednesday 3, 12 hours 30 minutes

Read more about Python DateTime Format.

Summary

In this tutorial of Python Examples, we learned how to convert a datetime object to string, with the help of well detailed examples.