Extended date and time

John Machin sjmachin at lexicon.net
Mon Nov 12 12:09:36 CET 2007


On Nov 12, 8:46 pm, Jeremy Sanders <jeremy
+complangpyt... at jeremysanders.net> wrote:
> John Machin wrote:
> > What does "dates in the past" mean?? Please be more specific about the
> > earliest date that you want to be able to handle. Python's datetime
> > starts at 0001-01-01. Somebody mentioned the time module, which is
> > implementation-dependent but typically starts at 1970-01-01 .
>
> > What functionality do you need, other than two-way conversion between
> > days_since_epoch and (proleptic Gregorian) date/time?
>
> I want to convert between seconds from the epoch (let's say 1970 in floating
> point) and date and time. I also want it to work across all platforms.
>
> Is there any way to convert a datetime into seconds from a certain date? Is
> the most robust way of doing it just to subtract two datetime objects and
> turn the timedelta into a floating point number?
>

That seems to be robust enough:

C:\junk>type epoch.py
import datetime
now = datetime.datetime(2007, 11, 12, 21, 20, 39, 859123)
for epoch_year in (1, 1970, 2070):
    EPOCH = datetime.datetime(epoch_year, 1, 1)
    print "\nepoch", repr(EPOCH)
    diff = now - EPOCH
    print "diff", repr(diff)
    sdiff = diff.microseconds / 1000000. \
        + diff.seconds + diff.days * 24. * 3600.
    print "sdiff", repr(sdiff)
    roundtrip = EPOCH + datetime.timedelta(seconds=sdiff)
    print "roundtrip", repr(roundtrip)
C:\junk>epoch.py

epoch datetime.datetime(1, 1, 1, 0, 0)
diff datetime.timedelta(732991, 76839, 859123)
sdiff 63330499239.859123
roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123)

epoch datetime.datetime(1970, 1, 1, 0, 0)
diff datetime.timedelta(13829, 76839, 859123)
sdiff 1194902439.859123
roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123)

epoch datetime.datetime(2070, 1, 1, 0, 0)
diff datetime.timedelta(-22696, 76839, 859123)
sdiff -1960857560.140877
roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123)

C:\junk>

Cheers,
John




More information about the Python-list mailing list