[Tutor] Time script help sought!
jfouhy at paradise.net.nz
jfouhy at paradise.net.nz
Tue Jan 11 22:20:38 CET 2005
Quoting "Jacob S." <keridee at jayco.net>:
> I don't think so. (correct me if I'm wrong) The datetime module is for
> making date and time instances that you can add and subtract to get
> timedelta objects. Other things involved of course, but I don't think it
> has anything to do with parsing and
> pretty printing columns of times. I'm not sure, don't quote me on it.
Partially correct ...
Firstly, datetime objects can produce string output using the strftime function.
Example:
>>> import datetime
>>> d = datetime.datetime(2004, 12, 31, hour=3, minute=27)
>>> d
datetime.datetime(2004, 12, 31, 3, 27)
>>> d.strftime("%A %B %d %Y, %I:%M%p")
'Friday December 31 2004, 03:27AM'
The old mx.datetime module (on which Python's datetime module is based, I
presume) had a strptime() function which would basically do the reverse (you
specify a format string and it would attempt to parse the date string you give
it). Unfortunately, Python's datetime module doesn't have such a function.
This is the best way I have found of doing it:
def strptime(s, format):
return datetime.datetime.fromtimestamp(time.mktime(time.strptime(s, format)))
Example:
>>> import time, datetime
>>> def strptime(s, format):
... return datetime.datetime.fromtimestamp(time.mktime(time.strptime(s,
format)))
...
>>> d = strptime('2004-12-31.23:59', '%Y-%m-%d.%H:%M')
>>> d.strftime("%A %B %d %Y, %I:%M%p")
'Friday December 31 2004, 11:59PM'
HTH.
--
John.
More information about the Tutor
mailing list