- Python strftime()
- Example 1: datetime to string using strftime()
- How strftime() works?
- Example 2: Creating string from a timestamp
- Format Code List
- Example 3: Locale’s appropriate date and time
- Python datetime to String
- Using strftime() method
- Format Directives
- Example: Python datetime to string format
- Example 1
- Example 2
- Example 3
- Example 4
- Example 5
- Bonus💰: Timestamp to String Python
- Conclusion
Python strftime()
The strftime() method returns a string representing date and time using date, time or datetime object.
Example 1: datetime to string using strftime()
The program below converts a datetime object containing current date and time to different string formats.
from datetime import datetime now = datetime.now() # current date and time year = now.strftime("%Y") print("year:", year) month = now.strftime("%m") print("month:", month) day = now.strftime("%d") print("day:", day) time = now.strftime("%H:%M:%S") print("time:", time) date_time = now.strftime("%m/%d/%Y, %H:%M:%S") print("date and time:",date_time)
When you run the program, the output will something like be:
year: 2018 month: 12 day: 24 time: 04:59:31 date and time: 12/24/2018, 04:59:31
Here, year , day , time and date_time are strings, whereas now is a datetime object.
How strftime() works?
In the above program, %Y , %m , %d etc. are format codes. The strftime() method takes one or more format codes as an argument and returns a formatted string based on it.
- We imported datetime class from the datetime module. It’s because the object of datetime class can access strftime() method.
- The datetime object containing current date and time is stored in now variable.
- The strftime() method can be used to create formatted strings.
- The string you pass to the strftime() method may contain more than one format codes.
Example 2: Creating string from a timestamp
from datetime import datetime timestamp = 1528797322 date_time = datetime.fromtimestamp(timestamp) print("Date time object:", date_time) d = date_time.strftime("%m/%d/%Y, %H:%M:%S") print("Output 2:", d) d = date_time.strftime("%d %b, %Y") print("Output 3:", d) d = date_time.strftime("%d %B, %Y") print("Output 4:", d) d = date_time.strftime("%I%p") print("Output 5:", d)
When you run the program, the output will be:
Date time object: 2018-06-12 09:55:22 Output 2: 06/12/2018, 09:55:22 Output 3: 12 Jun, 2018 Output 4: 12 June, 2018 Output 5: 09AM
Format Code List
The table below shows all the codes that you can pass to the strftime() method.
Directive | Meaning | Example |
%a | Abbreviated weekday name. | Sun, Mon, . |
%A | Full weekday name. | Sunday, Monday, . |
%w | Weekday as a decimal number. | 0, 1, . 6 |
%d | Day of the month as a zero-padded decimal. | 01, 02, . 31 |
%-d | Day of the month as a decimal number. | 1, 2, . 30 |
%b | Abbreviated month name. | Jan, Feb, . Dec |
%B | Full month name. | January, February, . |
%m | Month as a zero-padded decimal number. | 01, 02, . 12 |
%-m | Month as a decimal number. | 1, 2, . 12 |
%y | Year without century as a zero-padded decimal number. | 00, 01, . 99 |
%-y | Year without century as a decimal number. | 0, 1, . 99 |
%Y | Year with century as a decimal number. | 2013, 2019 etc. |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 00, 01, . 23 |
%-H | Hour (24-hour clock) as a decimal number. | 0, 1, . 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, . 12 |
%-I | Hour (12-hour clock) as a decimal number. | 1, 2, . 12 |
%p | Locale’s AM or PM. | AM, PM |
%M | Minute as a zero-padded decimal number. | 00, 01, . 59 |
%-M | Minute as a decimal number. | 0, 1, . 59 |
%S | Second as a zero-padded decimal number. | 00, 01, . 59 |
%-S | Second as a decimal number. | 0, 1, . 59 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000 — 999999 |
%z | UTC offset in the form +HHMM or -HHMM. | |
%Z | Time zone name. | |
%j | Day of the year as a zero-padded decimal number. | 001, 002, . 366 |
%-j | Day of the year as a decimal number. | 1, 2, . 366 |
%U | Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, . 53 |
%W | Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, . 53 |
%c | Locale’s appropriate date and time representation. | Mon Sep 30 07:06:05 2013 |
%x | Locale’s appropriate date representation. | 09/30/13 |
%X | Locale’s appropriate time representation. | 07:06:05 |
%% | A literal ‘%’ character. | % |
Example 3: Locale’s appropriate date and time
from datetime import datetime timestamp = 1528797322 date_time = datetime.fromtimestamp(timestamp) d = date_time.strftime("%c") print("Output 1:", d) d = date_time.strftime("%x") print("Output 2:", d) d = date_time.strftime("%X") print("Output 3:", d)
When you run the program, the output will be:
Output 1: Tue Jun 12 09:55:22 2018 Output 2: 06/12/18 Output 3: 09:55:22
Format codes %c , %x and %X are used for locale’s appropriate date and time representation.
We also recommend you to check Python strptime(). The strptime() method creates a datetime object from a string.
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 .
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.
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)
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)
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)
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)
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)
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)
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.
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.