Question: Convert datetime to long number

John Smith JohnSmith at obfs.com
Sun May 25 17:34:02 EDT 2003


Thanks. I used an awkward way to fix this before you guys posted.

def utctime(dt):
    return (((dt.toordinal()-719163)*24+dt.hour)*60+dt.minute)*60+dt.second


"Tim Peters" <tim_one at email.msn.com> wrote in message
news:mailman.1053880358.28162.python-list at python.org...
> [John Smith]
> >   A probably very simple question. How do I convert a datetime object to
> > the long number.  I mean if I do
> >
> > >>> x=datetime.utcnow(); a=time.time()
> > >>> x,a
> > (datetime.datetime(2003, 5, 25, 2, 2, 32, 540000), 1053828152.54)
> > >>>
> >
> > what function f I can apply to x such that  f(x) will return
1053828152.54
>
> It's hard to know whether you're asking about ways to convert between time
> zones, or asking about how to get a timestamp at all.  Assuming you're
> content to work in local time,
>
> >>> x = datetime.now(); a = time.time()
> >>> x, a
> (datetime.datetime(2003, 5, 25, 12, 12, 15, 830000), 1053879135.83)
> >>> time.mktime(x.timetuple())
> 1053879135.0
> >>> _ - a
> -0.83000004291534424
> >>>
>
> It's missing (only) the microseconds from the kind of timestamp
time.time()
> returns.  If you want those too, then
>
> >>> time.mktime(x.timetuple()) + x.microsecond / 1e6
> 1053879135.83
> >>> _ - a
> 0.0
> >>>
>
> If you need to work with UTC, then it's similar but more obscure:
>
> >>> x = datetime.utcnow(); a = time.time()
> >>> x, a
> (datetime.datetime(2003, 5, 25, 16, 24, 45, 730000), 1053879885.73)
> >>> calendar.timegm(x.utctimetuple())
> 1053879885
> >>> _ - a
> -0.73000001907348633
> >>> calendar.timegm(x.utctimetuple()) + x.microsecond / 1e6
> 1053879885.73
> >>> _ - a
> 0.0
> >>>
>
> datetime isn't keen to use floating-point timestamps, because what
> 1053879135.83 means varies across platforms (not all boxes start counting
at
> 1970, and boxes disagree about whether leap seconds should be counted),
and
> because a float doesn't have enough bits of precision to represent all the
> date+time combinations datetime can represent.  Support for timestamps in
> the datetime module is thus minimal -- we're trying to move away from
them.
>
> [Gerrit Holl]
> > You can use the strftime method, and pass "%s" as entry:
> >
> > datetime.datetime.utcnow().strftime("%s")
> >
> > Note that strftime returns an int, not a float.
>
> Sorry, strftime() returns a string, and doesn't have anything to do with
> timestamps regardless.  You may be thinking of strptime?
>
>






More information about the Python-list mailing list