[Tutor] Date and Time questions

Schmidt, Allen J. aschmidt@nv.cc.va.us
Mon, 9 Jul 2001 11:50:08 -0400


This is it! Perfect! 

Been using Zope for so long and could do this easily using the fmt attribute
of dtml-var.
Your solution offered something that matches what I have been used to. Just
did not know how to get it into a usable format to use the fmt attribute.

This is an email that will be added to my KnowledgeArsenal!
Thanks very much to you and all the suggestions offered!

-Allen

-----Original Message-----
From: Michael P. Reilly
[mailto:arcege@dsl092-074-184.bos1.dsl.speakeasy.net]
Sent: Monday, July 09, 2001 11:42 AM
To: aschmidt@nv.cc.va.us
Cc: tutor@python.org
Subject: Re: [Tutor] Date and Time questions


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              |