2

In JavaScript, I can assign:

var now = Date.now();

Then use now to calculate as a number variable

>>> import datetime
>>> datetime.datetime.now()
>>> datetime.datetime.today()

In python3, Using upper code doesnt seem helpful. Any idea what is equivalent of Date.now().

Machinexa
  • 626
  • 1
  • 8
  • 17
  • 1
    Start with `datetime.datetime.now().timestamp()`. See https://www.tutorialspoint.com/How-to-convert-Python-DateTime-string-into-integer-milliseconds – jarmod Oct 01 '20 at 13:37
  • Duplicate of [Get current time in milliseconds in Python?](https://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python) – trincot Oct 01 '20 at 13:50
  • Oh didnt realize that – Machinexa Oct 01 '20 at 13:55

2 Answers2

7

You should use time module.

>>> import time
>>> int(time.time() * 1000) #for getting the millisecs

1601559393404
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Equinox
  • 6,483
  • 3
  • 23
  • 32
0

Date.now() returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. The Python 3.3 and later equivalent is:

from datetime import datetime, timezone

now_ms = int(datetime.now(tz=timezone.utc).timestamp() * 1000)

Without tz=timezone.utc, datetime.timestamp will use a naive datetime, usually set to your local time with timezone, daylight savings time, etc. This can be a subtle source of bugs, when going from Python to Javascript, between development environments and production, or around daylight savings time transitions.

jwhitlock
  • 4,572
  • 4
  • 39
  • 49