Python time strftime() method
Description
The Python time strftime() function formats time, returning local time as a readable string. The format is determined by the format parameter.
Syntax
strftime() method syntax:
time.strftime(format[, t])
Parameters
- format -- the format string.
- t -- an optional parameter; t is a struct_time object.
Return Value
Returns the local time as a readable string.
Description
Date and time formatting symbols in Python:
- %y two-digit year (00-99)
- %Y four-digit year (0000-9999)
- %m month (01-12)
- %d day of the month (0-31)
- %H hour in 24-hour format (0-23)
- %I hour in 12-hour format (01-12)
- %M minutes (00-59)
- %S seconds (00-59)
- %a abbreviated local weekday name
- %A full local weekday name
- %b abbreviated local month name
- %B full local month name
- %c local date and time representation
- %j day of the year (001-366)
- %p local equivalent of A.M. or P.M.
- %U week number of the year (00-53), Sunday as the first day of the week
- %w weekday (0-6), Sunday as the first day of the week
- %W week number of the year (00-53), Monday as the first day of the week
- %x local date representation
- %X local time representation
- %Z name of the current time zone
- %% the % character itself
Example
The following example shows how to use the strftime() function:
Example
#!/usr/bin/python
-- coding: UTF-8 --
By importing the future package to be compatible with Python 3.x print
If you are using Python 3.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"
)
(
"year:"
,
year
)
month
=
now.
strftime
(
"%m"
)
(
"month:"
,
month
)
day
=
now.
strftime
(
"%d"
)
(
"day:"
,
day
)
time
=
now.
strftime
(
"%H:%M:%S"
)
(
"time:"
,
time
)
date_time
=
now.
strftime
(
"%Y-%m-%d, %H:%M:%S"
)
(
"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:28