How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC D Schuberts Piano Sonata D 850 in D
--
Chapters
00:00 Question
00:26 Accepted answer (Score 555)
00:43 Answer 2 (Score 284)
01:17 Answer 3 (Score 104)
01:52 Answer 4 (Score 18)
02:10 Thank you
--
Full question
https://stackoverflow.com/questions/6999...
Answer 1 links:
[timestamp]: https://docs.python.org/3/library/dateti...
Answer 2 links:
http://pleac.sourceforge.net/pleac_pytho...
[time.mktime]: http://docs.python.org/library/time.html...
[datetime.timetuple]: http://docs.python.org/library/datetime....
Answer 3 links:
http://delorean.readthedocs.org/en/lates...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #epoch
#avk47
--
Track title: CC D Schuberts Piano Sonata D 850 in D
--
Chapters
00:00 Question
00:26 Accepted answer (Score 555)
00:43 Answer 2 (Score 284)
01:17 Answer 3 (Score 104)
01:52 Answer 4 (Score 18)
02:10 Thank you
--
Full question
https://stackoverflow.com/questions/6999...
Answer 1 links:
[timestamp]: https://docs.python.org/3/library/dateti...
Answer 2 links:
http://pleac.sourceforge.net/pleac_pytho...
[time.mktime]: http://docs.python.org/library/time.html...
[datetime.timetuple]: http://docs.python.org/library/datetime....
Answer 3 links:
http://delorean.readthedocs.org/en/lates...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #epoch
#avk47
ACCEPTED ANSWER
Score 570
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
ANSWER 2
Score 107
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
ANSWER 3
Score 18
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
ANSWER 4
Score 15
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000