Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Schif Schaf
September 20, 2009, 2:22 am
rate this thread
The other day I needed to convert a date like "August 2009" into a
"seconds-since-epoch" value (this would be for the first day of that
month, at the first second of that day).
In Python, I came up with this:
time_in_sse = time.mktime(
datetime.datetime(2009, 8, 1).timetuple()
I *wanted* to just use time.mktime(), but it wouldn't work unless I
could specify the *complete* time tuple value (who would have all that
handy?!). I also wanted to then just do datetime.datetime
(...).secs_since_epoch(), but it didn't support a function like that
-- not one I could find anyway.
Note, to arrive at that above solution, I had to spend a fair amount
of time reading the docs on both the time and datetime modules, and
then wondering why the methods I wanted weren't there. Am I missing
something and maybe used the wrong methods/modules here?
Contrast this to Perl, where the solution I came up with in about 5
my $dt = DateTime->new(year => 2009, month => 8);
print $dt->epoch, "\n";
(it only took 5 minutes because the docs for DateTime tell you exactly
what you want to know right at the top on the first page of the docs.)
Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
To be fair, the docs for the time module (I'm looking at the help file
for 2.6.2) are written in such a way that it's not clear you can use
zero for the unknown day of the week or day of the year. The passage
for time.mktime(t) that states "If the input value cannot be
represented as a valid time, either OverflowError or ValueError will
be raised" *might* imply that your tuple is invalid, because
2009-08-01 was not a Monday and 0 is not even in the valid range for
tm_yday. In my opinion, this is a deficiency of the docs.
On the other hand, I think the OP, as well as users of Python in
general, should probably not be so timid. Just try something and see
if it works. Throw zeros in for the unknown values and maybe you'll
get a ValueError (like your cautious, doc-respecting mind is
expecting) or maybe the routine will actually do the appropriate and
convenient thing and trust your year, month, and day. In this case,
the latter is happily true.
For what it's worth, it's true that the time module is not
particularly Pythonic. It's mostly a wrapper for C library functions,
and the docs do imply this near the top. Personally, I think the
wrapper could stand to be less thin and provide friendlier access
while still using the C library, but I doubt it's a big enough pain
point to spur anyone to improve it.
- » FAQ 8.35 How do I close a process's filehandle without waiting for it to complete?
- — Next thread in » PERL Discussions
- » FAQ 4.73 How do I keep persistent data across program calls?
- — Previous thread in » PERL Discussions