I'm using highcharts and I'm parsing a json in a Django webservice to send it to my viewer.
What I'm struggling to do is to get a date.utc("1970,9,21")
output in python.
What's the easiest way to emulate this javascript function in python?
I'm using highcharts and I'm parsing a json in a Django webservice to send it to my viewer.
What I'm struggling to do is to get a date.utc("1970,9,21")
output in python.
What's the easiest way to emulate this javascript function in python?
To emulate Date.UTC()
from javascript in Python:
#!/usr/bin/env python3
from datetime import datetime, timedelta
assert year > 100
utc_time = datetime(year, month, day, hours, minutes, seconds, ms*1000)
millis = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1)
The input is UTC time. Hours, minutes, seconds, ms are optional. The method returns the number of (non-leap) milliseconds since January 1, 1970, 00:00:00 UTC.
To emulate / timedelta(milliseconds=1)
on Python 2:
#!/usr/bin/env python
from __future__ import division
from datetime import datetime, timedelta
def to_millis(utc_time, epoch=datetime(1970,1,1)):
td = utc_time - epoch
assert td.resolution >= timedelta(microseconds=1)
# return td.total_seconds()*1000 analog
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**3
Use //
to get an integer instead of a floating-point number.
Example:
>>> import datetime
>>> (datetime.date(1970,9,21) - datetime.date(1970, 1, 1)).days * 86400000
22723200000
According to your comment @Stevanicus I want a string similar to 1107216000000 – azelix
This is probably what you're looking for:
>>> from time import time
>>> time()
1447064407.092834
>>>
Or you could use calendar.timegm()
which delivers a UTC result no matter the local time settings.
>>> import calendar
>>> import datetime
>>> d = datetime.datetime(2015, 11, 9)
>>> calendar.timegm(d.timetuple())
1447027200
>>>