python-3.xpython-dateutil

Python 3 Convert ISO 8601 to milliseconds


I'm receiving an ISO 8601 format from an API GET request ("2020-02-25T00:02:43.000Z"). I'm trying to convert it to milliseconds, because that format is required in the payload of the API POST call. I've been successful running the code from a Linux system, but I get ValueError: Invalid format string from Windows.

From Linux:

import dateutil.parser

time = "2020-02-25T00:02:43.000Z"
parsed_time = dateutil.parser.parse(time)
t_in_millisec = parsed_time.strftime('%s%f')
t_in_millisec[:-3]

returns

'1582588963000'

From Windows:

import dateutil.parser

      1 time = "2020-02-25T00:02:43.000Z"
      2 parsed_time = dateutil.parser.parse(time)
----> 3 t_in_millisec = parsed_time.strftime('%s%f')

ValueError: Invalid format string

Is there a way around this?


Solution

  • Here is the list of what works on windows and indeed the %s is not present. https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strftime-wcsftime-strftime-l-wcsftime-l?redirectedfrom=MSDN&view=vs-2019

    I always use datetime, if you have the opportunity to use it here is an example :

    datetime.datetime(2020,2,25,0,2,43).timestamp()
    

    or

    import datetime
    time = "2020-02-25T00:02:43.000Z"
    date = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S.%fZ')
    timestamp = str((date - datetime.datetime(1970, 1, 1)).total_seconds()*1000)
    print(timestamp[:-2])