How to convert Python Datetime to String?
Python - Convert 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.
Syntax
The syntax of str() builtin function to convert datetime object to string is
datetimeString = str(datetimeObject)
The syntax of strftime() function to convert datetime object to string is
datetimeString = datetimeObject.strftime(format_string)
Examples for both of these scenarios are given below.
Examples
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))
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])
Output
2019-12-10
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(' '))
Output
2020-01-01 12:30:59
2020-01-01 12:30:59
2. 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)
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.