Time
Contents
Time¶
Converting between time and date formats is a common task but one that is deceptively tricky. Tt can be difficult to keep track of what days or times are being referenced while dealing with different date formats, time zones, daylight savings time, and so on. Fortunately for us, Python has several modules that make it somewhat easier.
![clock](../_images/clock.webp)
Standard date formats¶
Despite there being several different date formats (e.g. D M Y or M D Y), the International Organization for Standardization (ISO) developed a standardized format called ISO 8601 to facilitate the worldwide exchange and communication of date and time-related data. According to this format, date and time values are ordered from the largest to smallest unit of time: year, month (or week), day, hour, minute, second:
YYYY-MM-DD hh:mm:ss
Computer time¶
Most of the computers count time from an arbitrary instant called the Unix epoch. This arbitrary date is January 1st, 1970, at 00:00:00 hours UTC. Coordinated Universal time (UTC) refers to the time at 0° longitude, popularly known as Greenwich Meridian Time (GMT). It is not adjusted for daylight saving time so there are always twenty-four hours in every day.
We can print the current Unix time using the built-in time
module which has a method called time()
that returns the current time as a floating point number expressed in seconds since the Unix epoch, in UTC:
import time
# Define a variable that represents current time
unix_time = time.time()
print(int(unix_time))
1655075482
Note
Note that unix_time
updates every time we run this code block. We also used int
to convert the floating point number to an integer for better readability.
The number returned by time()
may be converted into a more common time format (i.e. year, month, day, hour, etc.) in UTC by passing it to either gmtime()
, which returns time in UTC, or localtime()
, which returns local time.
time.gmtime()
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=12, tm_hour=23, tm_min=11, tm_sec=23, tm_wday=6, tm_yday=163, tm_isdst=0)
time.localtime()
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=12, tm_hour=16, tm_min=11, tm_sec=23, tm_wday=6, tm_yday=163, tm_isdst=1)
These two functions return a struct_time
object with a named tuple interface. In other words, values in this object can be accessed by their index or by attribute name. The year, month, and day can therefore be printed by typing:
local = time.localtime()
# Print year, month, and day using index of struct_time object
local[0], local[1], local[2]
(2022, 6, 12)
Or:
# Print year, month, and day using attribute name of struct_time object
local.tm_year, local.tm_mon, local.tm_mday
(2022, 6, 12)
Convert a struct_time
object to a standard time format¶
We can print the current time in the ISO 8601 standard format (i.e. YYYY-MM-DD hh:mm:ss
) using the strftime
function. This function takes two arguments. The first argument is a string which specifies the output format. The second argument (after the comma) specifies the time we want to convert.
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2022-06-12 16:11:24'
We can print the current time in any way we like.
time.strftime("%a, %b %d %Y %I:%M:%S %p %Z", time.localtime())
'Sun, Jun 12 2022 04:11:24 PM PDT'
Note
For more options see the following table.
Convert a string to a standard time format¶
Sometimes we are presented with strangely formatted dates and times that we would like to convert to a standard format. We can do that using the strptime
function. This function takes two arguments, a string that represents the time that we have been given and another string that specifies the format it is in.
time.strptime('11/30/2022', "%m/%d/%Y")
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=334, tm_isdst=-1)
We could then use strftime
to convert this struct_time
object into standard time format.
time.strftime("%Y-%m-%d %H:%M:%S", time.strptime('11/30/2022', "%m/%d/%Y"))
'2022-11-30 00:00:00'
Convert integers to standard time format¶
Another common case is when we have a spreadsheet that contains the year, month, day etc. in separate columns as integers. We can convert these integers into a single string variable by first using the built-in function str
to convert the integers to strings and then using the +
sign to concatenate the the individual strings.
year = 2022
month = 11
day = 30
time_string = str(year) + str(month) + str(day)
time.strptime(time_string, "%Y%m%d")
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=334, tm_isdst=-1)
t = time.strptime(time_string, "%Y%m%d")
time.strftime("%Y-%m-%d %H:%M:%S", t)
'2022-11-30 00:00:00'
Note
The time
library provides most of what we need but there are other Python libraries such as datetime
and dateutil
that provide even more functionality for manipulating dates and time. Pandas
also contains extensive capabilities and features for working with time series data which we will cover in Week 7.