[Tutor] Date and Time questions

Michael P. Reilly arcege@speakeasy.net
Mon, 9 Jul 2001 11:41:57 -0400 (EDT)


Schmidt, Allen J. wrote
> 
> I have looked around for things that deal with Date and Time.
> All I want to do is be able to assign a date/time value to a variable. Like
> 20010709_18:05.
> Does not need to be a date object just a text string that I can use to drop
> into a database table or use in other ways. 

Date formatting is complicated because different software systems use
different formats for the dates.  Remember that the infamous Y2K "bugs"
were because of date formatting.

Most computers keep track of time as the number of seconds since what
is called the Epoch, approxiately 1970.  Everything else is just a
re-formatting of that count.

To add to the complexity, there are timezones (which are not all equal)
and daylight savings time, which doesn't exist everywhere.

First, get the current time, then convert it to the local timezone,
adjusting for daylight savings, then to a string.  If you are looking
for a filename, then it is a bad idea to use the ctime output, it doesn't
sort well and contains spaces.

>>> import time
>>> curtime = time.time()
>>> curtime = time.time()
>>> curlcltime = time.localtime(curtime)
>>> print curtime, curlcltime
994692772.858 (2001, 7, 9, 11, 32, 52, 0, 190, 1)
>>> print time.asctime(curlcltime)
Mon Jul  9 11:32:52 2001
>>> print time.ctime(curtime)
Mon Jul  9 11:32:52 2001
>>> fmt = '%Y%m%d_%H:%M'  # set the output format: YYYYMMDD_HH:MM
>>> print time.strftime(fmt, curlcltime)
20010709_11:32
>>> (year, month, day, hour, min, sec, wday, yday, dst) = curlcltime
>>> print '%4d%02d%02d_%02d:%02d' % (year, month, day, hour, min)

With strftime, you can create just about any string you like, but you
also can do the same with accessing the items in the tuple returned
by time.localtime().

You might also want to look at the wxDateTime package.

Good luck,
  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |