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'>.
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.
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:
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.
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.
Directive | Description | Example |
---|---|---|
%a | Abbreviated weekday name | Sun, Mon, ..., Sat |
%A | Full weekday name | Sunday, Monday, ..., Saturday |
%b | Abbreviated month name | Jan, Feb, ..., Dec |
%B | Full month name | January, February, ..., December |
%c | Locale's date and time representation | Tue Mar 27 11:45:40 2018 |
%d | Day of the month as a zero-padded decimal number | 01, 02, ..., 31 |
%H | Hour (24-hour clock) as a zero-padded decimal number | 00, 01, ..., 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number | 01, 02, ..., 12 |
%j | Day of the year as a zero-padded decimal number | 001, 002, ..., 366 |
%m | Month as a zero-padded decimal number | 01, 02, ..., 12 |
%M | Minute as a zero-padded decimal number | 00, 01, ..., 59 |
%p | Locale's equivalent of AM or PM | AM, PM |
%S | Second as a zero-padded decimal number | 00, 01, ..., 59 |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number | 00, 01, ..., 53 |
%w | Weekday as a decimal number (0 is Sunday) | 0, 1, ..., 6 |
%W | Week number of the year (Monday as the first day of the week) as a zero-padded decimal number | 00, 01, ..., 53 |
%x | Locale's date representation | 03/27/18 |
%X | Locale's time representation | 10:24:55 |
%y | Year without century as a zero-padded decimal number | 00, 01, ..., 99 |
%Y | Year with century as a decimal number | 0001, 0002, ..., 2018, 2019, ..., 9998, 9999 |
%z | UTC offset in the form +HHMM or -HHMM | +0000, -0400, +1030 |
%Z | Time 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.
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.
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.
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.
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.
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.
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.
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!😊