Converting date to milliseconds since 1-1-70

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • NateM

    #1

    Converting date to milliseconds since 1-1-70

    How do I convert any given date into a milliseconds value that
    represents the number of milliseconds that have passed since January 1,
    1970 00:00:00.000 GMT?
    Is there an easy way to do this like Date in java?
    Thanks,
    Nate

  • gry@ll.mit.edu

    #2
    Re: Converting date to milliseconds since 1-1-70

    NateM wrote:[color=blue]
    > How do I convert any given date into a milliseconds value that
    > represents the number of milliseconds that have passed since January 1,
    > 1970 00:00:00.000 GMT?
    > Is there an easy way to do this like Date in java?
    > Thanks,
    > Nate[/color]

    The main module for dates and times is "datetime"; so
    [color=blue][color=green][color=darkred]
    >>> import datetime
    >>> t=datetime.date time.now()
    >>> print t[/color][/color][/color]
    2006-01-24 15:13:35.012755

    To get at the "epoch" value, i.e. seconds since 1/1/1970, use the
    "time" module:
    [color=blue][color=green][color=darkred]
    >>> import time
    >>> print time.mktime(t.t imetuple())[/color][/color][/color]
    1138133615.0

    Now just add in the microseconds:[color=blue][color=green][color=darkred]
    >>> epoch=time.mkti me(d.timetuple( ))+(t.microseco nd/1000000.)
    >>> print epoch[/color][/color][/color]
    1138133615.01

    Use the "%" formatting operator to display more resolution:[color=blue][color=green][color=darkred]
    >>> print '%f' % t[/color][/color][/color]
    1138133615.0127 55

    Note that the floating point division above is not exact and could
    possibly
    mangle the last digits.

    Another way to this data is the datetime.strfti me member:
    [color=blue][color=green][color=darkred]
    >>> print d.strftime('%s. %%06d') % d.microsecond[/color][/color][/color]
    '1138133615.012 755'

    This gets you a string, not a number object. Converting the string to
    a number again risks inaccuracy in the last digits:[color=blue][color=green][color=darkred]
    >>> print float( '1138133615.012 755')[/color][/color][/color]
    1138133615.0127 549

    Comment

    • NateM

      #3
      Re: Converting date to milliseconds since 1-1-70

      Thank you! If I am reading in dates as strings from a text file, like
      "5/11/1998", how do I convert that to a format I can pass into mktime?
      Thanks again.

      Comment

      • Xavier Morel

        #4
        Re: Converting date to milliseconds since 1-1-70

        NateM wrote:[color=blue]
        > Thank you! If I am reading in dates as strings from a text file, like
        > "5/11/1998", how do I convert that to a format I can pass into mktime?
        > Thanks again.
        >[/color]
        Check time.strptime()

        Comment

        Working...