471,309 Members | 1,404 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,309 software developers and data experts.

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

Jan 24 '06 #1
3 12220
gry
NateM wrote:
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


The main module for dates and times is "datetime"; so
import datetime
t=datetime.datetime.now()
print t 2006-01-24 15:13:35.012755

To get at the "epoch" value, i.e. seconds since 1/1/1970, use the
"time" module:
import time
print time.mktime(t.timetuple()) 1138133615.0

Now just add in the microseconds: epoch=time.mktime(d.timetuple())+(t.microsecond/1000000.)
print epoch 1138133615.01

Use the "%" formatting operator to display more resolution: print '%f' % t 1138133615.012755

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.strftime member:
print d.strftime('%s.%%06d') % d.microsecond '1138133615.012755'

This gets you a string, not a number object. Converting the string to
a number again risks inaccuracy in the last digits: print float( '1138133615.012755')

1138133615.0127549

Jan 24 '06 #2
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.

Jan 24 '06 #3
NateM wrote:
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.

Check time.strptime()
Jan 26 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Gary Smith | last post: by
9 posts views Thread by Alok yadav | last post: by
3 posts views Thread by Jef Driesen | last post: by
4 posts views Thread by gubbachchi | last post: by
1 post views Thread by =?Utf-8?B?bGF3ODc4Nw==?= | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.