The time Module
The time module provides a number of functions that deal with dates and the
time within a day. It’s a thin layer on top of the C runtime library.
A given date and time can either be represented as a floating-point value (the number of seconds since a reference date, usually January 1, 1970), or as a time tuple.
Getting the Current Time
Example 1-79 shows how you can use the time module to get the current time.
Example 1-79. Using the time Module to Get the Current Time
File: time-example-1.py import time now = time.time() print now, "seconds since", time.gmtime(0)[:6] print print "or in other words:" print "- local time:", time.localtime(now) print "- utc:", time.gmtime(now)937758359.77 seconds since (1970, 1, 1, 0, 0, 0)or in other words:- local time: (1999, 9, 19, 18, 25, 59, 6, 262, 1)- utc: (1999, 9, 19, 16, 25, 59, 6, 262, 0)
The tuple returned by localtime and
gmtime contains the year, month, day, hour, minute,
second, day of the week, day of the year, daylight savings flag. The
year
number is four digits, the day of week begins with 0 for Monday,
and January 1 is day number 1.
Converting Time Values to Strings
You can of course use standard string-formatting operators to convert
a time tuple to a string, but the time module also
provides a number of standard conversion functions, as Example 1-80 illustrates.
Example 1-80. Using the time Module to Format Dates and Times
File: time-example-2.py import time now = time.localtime(time.time()) print time.asctime(now) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access