The localtime()
function in the time
module converts seconds representing time since the epoch into local time in form of a struct_time
object. A struct_time
object contains information about the represented date such as the year, month, day, hour, minute, second, weekday, and day of the year.
localtime(secs = None)
secs |
An optional arguments representing the seconds to be converted into a local time. |
The function returns a struct_time
object representing the local time, represented by the given seconds.If the seconds are not given, it returns the current local time.
Using the localtime()
function seconds given.
#import time module
import time
#without any argument
now = time.localtime()
print(now)
Use the localtime()
function with seconds given
import time
yesterday= time.localtime(time.time() - 86400)
# Print yesterday's time
print("Year: ", yesterday.tm_year)
print("Month: ", yesterday.tm_mon)
print("Day: ", yesterday.tm_mday)
print("Hour: ", yesterday.tm_hour)
print("Minute: ", yesterday.tm_min)
print("Second: ", yesterday.tm_sec)
Converting struct_time into a string
We can convert the struct_time
object into a formatted more human-friendly date using the
strftime()
function.
strftime(format, t = None)
format |
a string containing the format of the date (e.g. "%d/%m/%Y " for DD/MM/YYYY) |
t | An optional argument representing the struct_time object we wish to convert. If not given it defaults to the current moment. |
Convert struct_time
object into a formatted string
import time
#Today's date as a string
today = time.localtime()
formatted_today = time.strftime("%d %b %Y %I:%M:%S %p", today)
print(formatted_today)
#yesterday's time as a string
yesterday= time.localtime(time.time() - 86400)
formatted_yesterday = time.strftime("%d %b %Y %I:%M:%S %p", yesterday)
print(formatted_yesterday)
The following table summarizes some of the formatting parameters.
parameter | description |
---|---|
%a |
Abbreviated weekday name |
%A |
Full weekday name |
%b |
Abbreviated month name |
%B |
Full month name |
%d |
The day of the month, [0, 31] |
%H |
Hour (24-hour clock) as a decimal number [00,23] |
%I |
Hour (12-hour clock) as a decimal number [01,12] |
%j |
Day of the year as a decimal number [001,366] |
%m |
Month as a decimal number [01,12] |
%M |
Minute as a decimal number [00,59] |
%p |
Locale’s equivalent of either AM or PM |
%S |
Second as a decimal number [00,61] |
%U |
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53] |
%w |
Weekday as a decimal number [0(Sunday),6] |
%W |
Week number of the year (Monday as the first day of the week) as a decimal number [00,53] |
%x |
Date representation. |
%X |
time representation. |
%y |
Year without century, [00 - 99] |
%Y |
Year with century as a decimal number |
%z |
UTC offset in the form +HHMM or -HHMM |
%Z |
Timezone name. |