Time

John Machin sjmachin at lexicon.net
Fri May 11 19:45:05 EDT 2007


On May 12, 7:46 am, HMS Surprise <j... at datavoiceint.com> wrote:

[first message]

HS ==> I need to convert the string below into epoch seconds so that I
can
perform substractions and additions.

JM ==> I presume you mean "seconds since the epoch". You don't need to
do that.

HS ==> I assume I will need to break it
up into a time_t struct and use mktime.

JM ==> You assume wrongly. The time module exists (IMVHO) solely as a
crutch for people who are converting C etc code that uses the time.h
functions from the C standard library. If you are starting off from
scratch, use the Python datetime module -- especially if you need to
store and manipulate pre-1970 dates; e.g. the date of birth of anyone
aged more than about 37.5 years :-)

HS ==> Two questions if you will
please:

Is there a way to use multiple separator characters for split similar
to awk's [|] style?

JM ==> Only if you can find such a way in the manual.

HS ==> Could you point to an example of a python time_t struct?

JM ==> Python doesn't have that; it's a C concept


HS ==> 05/11/2007 15:30

[second message]

HS==> > Could you point to an example of a python time_t struct?

Or maybe that should be a tm struct???

JM ==> See previous answer.

[third message]

HS ==> Sorry, reading a little closer I see that the time tuple is
apparently
an ordinary list.

JM ==> Huh? A tuple is a tuple. A tuple is not a list, not even a very
extraordinary one.

If you are desperate to use the time module, try this:

>>> import time
>>> s = "05/11/2007 15:30"
>>> fmt = "%m/%d/%Y %H:%M"
# Given the current date, I'm presuming that your example indicates
that you adhere to the "month-first-contrary-to-common-sense"
religion :-)
>>> time.strptime(s, fmt)
(2007, 5, 11, 15, 30, 0, 4, 131, -1)

otherwise:

>>> import datetime
>>> d1 = datetime.datetime.strptime(s, fmt)
>>> d1
datetime.datetime(2007, 5, 11, 15, 30)
>>> d2 = datetime.datetime(2007, 5, 1)
>>> d2
datetime.datetime(2007, 5, 1, 0, 0)
>>> delta = d1 - d2
>>> delta
datetime.timedelta(10, 55800)
>>> days_diff = delta.days + delta.seconds / 60. / 60. / 24.
>>> days_diff
10.645833333333334

Do read the datetime module documentation for more info ... in
particular the timedelta object has a microseconds attribute; in
general there is a whole heap of functionality in there.

HTH,
John




More information about the Python-list mailing list