[Tutor] Date to seconds conversion
Anna Ravenscroft
revanna@mn.rr.com
Mon Apr 7 15:35:02 2003
On Sunday 06 April 2003 22:22, Antone wrote:
> What is the easiest way to convert a date (03/03/2003) to seconds?
If you're looking for "seconds from the epoch", use the time module in
python's standard library.
http://www.python.org/doc/current/lib/module-time.html
localtime([secs])
Like gmtime() but converts to local time. The dst flag is set to 1 when DST
applies to the given time. Changed in version 2.1: Allowed secs to be
omitted.
mktime(tuple)
This is the inverse function of localtime(). Its argument is the full 9-tuple
(since the dst flag is needed; use -1 as the dst flag if it is unknown) which
expresses the time in local time, not UTC. It returns a floating point
number, for compatibility with time(). If the input value cannot be
represented as a valid time, either OverflowError or ValueError will be
raised (which depends on whether the invalid value is caught by Python or the
underlying C libraries). The earliest date for which it can generate a time
is platform- dependent.
time()
Return the time as a floating point number expressed in seconds since the
epoch, in UTC. Note that even though the time is always returned as a
floating point number, not all systems provide time with a better precision
than 1 second. While this function normally returns non-decreasing values, it
can return a lower value than a previous call if the system clock has been
set back between the two calls.
Some samples of the code:
>>> import time
>>> time.localtime()
(2003, 4, 7, 14, 30, 38, 0, 97, 1)
>>> time.mktime((2003, 4, 7, 14, 30, 38, 0, 97, 1))
1049743838.0
>>> time.mktime((2003, 03, 04, 0, 0, 0, 0, 0, 0))
1046757600.0
>>>
Hope this helps.
Anna