The strftime() function converts a datetime object (representing the current date and time) into a string based on a specified format.
Example 1: datetime to string
Visual Representation
from datetime import datetime
# Create a datetime object
current_date_time = datetime.now()
print(current_date_time)
print(type(current_date_time))
# Specify the format for the string
format = "%Y-%m-%d %H:%M:%S"
# Convert the datetime object to a string
datetime_string = current_date_time.strftime(format)
print(datetime_string)
print(type(datetime_string))
Output
2023-10-18 21:18:57.148694
<class 'datetime.datetime'>
2023-10-18 21:18:57
<class 'str'>
Example 2: Extracting and Formatting Individual Date and Time
Current day
Current month
Current year
Current time
Current date and time
from datetime import datetime
# current date and time
current_date_time = datetime.now()
# current day
day = current_date_time.strftime("%d")
print("day:", day)
# current month
month = current_date_time.strftime("%m")
print("month:", month)
# current year
year = current_date_time.strftime("%Y")
print("year:", year)
# current time
time = current_date_time.strftime("%H:%M:%S")
print("time:", time)
# current date and time
date_time = current_date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:", date_time)
Output
Table of the date and time component
Format Code | Description | Example Output |
---|---|---|
%Y | Year with century | 2023 |
%y | Year without century | 23 |
%m | Month as a zero-padded number | 10 |
%B | Full month name | October |
%b | Abbreviated month name | Oct |
%d | Day of the month as a zero-padded number | 18 |
%A | Full weekday name | Wednesday |
%a | Abbreviated weekday name | Wed |
%H | Hour (24-hour clock) as a zero-padded number | 21 |
%I | Hour (12-hour clock) as a zero-padded number | 09 |
%p | AM or PM | PM |
%M | Minute as a zero-padded number | 18 |
%S | Second as a zero-padded number | 57 |
%Z | Time zone name | IST |
%z | UTC offset | +0530 |
%c | Locale’s appropriate date and time | Wed Oct 18 21:18:57 2023 IST |
%x | Locale’s appropriate date | 10/18/23 |
%X | Locale’s appropriate time | 21:18:57 |
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.