1

I have a date in this format 04-07-2018 the following Javascript produces

const date1 = new Date("04-07-2018").getTime();
date1; // 1523084400000

how do I parse the date and convert them to milliseconds in python

e.iluf
  • 1,389
  • 5
  • 27
  • 69
  • Might be already answered here https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p – Chai Ang Oct 26 '18 at 23:10
  • Possible duplicate of [How can I convert a datetime object to milliseconds since epoch (unix time) in Python?](https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p) – soundstripe Oct 27 '18 at 00:38

2 Answers2

1

We can perform this in three steps:

  1. first we convert the string to a datetime object;
  2. next we calculate the difference between that datetime object and the first of January, 1970;
  3. we calculate this difference in seconds, and then multiply it with 1000.

For example:

from datetime import datetime

def total_millis(text):
    dt = datetime.strptime(text, '%m-%d-%Y')
    return 1000 * (dt - datetime(1970, 1, 1)).total_seconds()

This implementation however is timezone independent, whereas the JavaScript version depends on the timezone.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

The JavaScript getTime() method returns the number of milliseconds since January 1, 1970 00:00:00.

You can use datetime but you should compute it with a deltatime object since according to this Python doesn't guarantee any particular epoch time

import datetime
delta = datetime.datetime(2018, 4, 7) - datetime.datetime(1970, 1, 1)
milliseconds = delta.total_seconds()*1000 # 1523059200000.0
kilgoretrout
  • 3,547
  • 5
  • 31
  • 46