Python time strftime() Method
Description
The Python time strftime() function is used to format time, returning local time represented as a readable string, with the format determined by the format parameter.
Syntax
strftime() method syntax:
time.strftime(format[, t])
Parameters
- format -- Format string.
- t -- The optional parameter t is a struct_time object.
Return Value
Returns local time represented as a readable string.
Notes
Python time and date formatting symbols:
- %y Two-digit year representation (00-99)
- %Y Four-digit year representation (000-9999)
- %m Month (01-12)
- %d Day of the month (0-31)
- %H 24-hour format hour (0-23)
- %I 12-hour format hour (01-12)
- %M Minutes (00=59)
- %S Seconds (00-59)
- %a Locale abbreviated weekday name
- %A Locale full weekday name
- %b Locale abbreviated month name
- %B Locale full month name
- %c Locale appropriate date and time representation
- %j Day of the year (001-366)
- %p Locale equivalent of A.M. or P.M.
- %U Week number of the year (00-53) with Sunday as the first day of the week
- %w Weekday (0-6), with Sunday as the first day of the week
- %W Week number of the year (00-53) with Monday as the first day of the week
- %x Locale appropriate date representation
- %X Locale appropriate time representation
- %Z Name of the current time zone
- %% The % character itself
Example
The following example demonstrates the usage of the strftime() function:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Import the __future__ package to make print compatible with Python3.x
# If you are using Python3.x, you can remove this import line
from __future__ import print_function
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("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)
# -*- coding: UTF-8 -*-
# Import the __future__ package to make print compatible with Python3.x
# If you are using Python3.x, you can remove this import line
from __future__ import print_function
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("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)
The output of the above example is:
year: 2020 month: 09 day: 25 time: 10:24:28 date and time: 2020-09-25, 10:24:28Other Extensions