in this python tutorial, I’ll explore ways to convert DateTime object to string. I have already shared an tutorial Convert string to DateTime in Python.
We’ll use the strftime()
method to convert Datetime into string in Python. This method is part of Python datetime module, it provides classes for manipulating dates and times.
Convert datetime object to a string
The Python datetime module includes strftime()
method to convert a datetime object to a string. This method allows you to specify the format of the output string.
from datetime import datetime
# Assuming you have a datetime object
dt = datetime.now()
# Convert datetime to string
date_string = dt.strftime("%Y-%m-%d %H:%M:%S")
print("Datetime to string:", date_string)
The strftime()
method are having the following parameters:
- %Y represents the year (four digits)
- %m represents the month (zero-padded)
- %d represents the day of the month (zero-padded)
- %H represents the hour (24-hour clock, zero-padded)
- %M represents the minute (zero-padded)
- %S represents the second (zero-padded)
Datetime object to a string in Python
Python provides the pytz library for timezone support. You can use pytz with datetime objects to represent timezones and perform conversions between different timezones.
xxxxxxxxxx
import pytz
from datetime import datetime
dt = datetime.now(pytz.timezone('America/New_York'))
date_string = dt.strftime("%Y-%m-%d %H:%M:%S %Z")
print("Datetime with timezone to string:", date_string)
%Z
represents the timezone name.
Conver DateTime object to a string Using the arrow
Arrow library provides a format()
method, that can be used to convert an Arrow object to a string with a specified format.
xxxxxxxxxx
import arrow
dt = arrow.now()
date_string = dt.format("YYYY-MM-DD HH:mm:ss")
Convert Datetime object to a string Using dateutil
The dateutil
library provides the parser.parse()
function, which can parse a wide range of date and time formats and return a datetime object. You can then use the strftime()
method to convert the datetime object to a string.
xxxxxxxxxx
from dateutil import parser
date_string = "2024-02-26 15:30:00"
parsed_datetime = parser.parse(date_string)
formatted_string = parsed_datetime.strftime("%Y-%m-%d %H:%M:%S")
Conclusion
We have learned different ways to convert datetime objects to strings. We have explored strftime()
method, along with other libraries like pytz, dateutil, and Arrow, that are used to convert DateTime objects into strings.