0

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?

azelix
  • 1,257
  • 4
  • 26
  • 50

2 Answers2

1

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

See Converting datetime.date to UTC timestamp in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

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
>>>
Torxed
  • 22,866
  • 14
  • 82
  • 131
  • You don't need calendar for that: `>>> d.timestamp() 1447023600.0` – MKesper Nov 09 '15 at 12:15
  • @MKesper correct me if I'm wrong but `timestamp()` will honor your local time setting, which will differ from *Nix and Windows? – Torxed Nov 09 '15 at 12:51
  • [The docs](https://docs.python.org/3.5/library/datetime.html#datetime.datetime.timestamp) say: Note There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc: `timestamp = dt.replace(tzinfo=timezone.utc).timestamp()` or by calculating the timestamp directly: `timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)` – MKesper Nov 09 '15 at 14:55
  • `timegm()` converts **UTC time** to POSIX timestamp. Do not pass it `datetime.now()` (the local time). – jfs Nov 09 '15 at 17:33
  • @J.F.Sebastian Fixed. – Torxed Nov 09 '15 at 17:34