0

I'm receiving an ISO 8601 formatted timestamp 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.

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]

From Linux it 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?

0

3 Answers 3

17

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])
Sign up to request clarification or add additional context in comments.

Comments

7

In Python 3.7 the method datetime.fromisoformat was added. So you can now do:

from datetime import datetime

my_iso_timestamp = "2020-02-25T00:02:43.000Z"
s_since_epoch = datetime.fromisoformat(my_iso_timestamp).timestamp()

# datetime.timestamp returns a float - the number of seconds since epoch 
# as the integer part and microseconds and the fraction.
ms_since_epoch = int(s_since_epoch * 1000)

Comments

4

The reason this doesn't work in Windows is that the strftime function calls the native OS's C library, and Unix ticks (i.e. seconds since midnight on Jan 1, 1970) aren't a part of the Windows operating system.

If you want to get the number of seconds since Jan 1, 1970, then you can simply subtract the original date and get the total seconds from the timedelta. Python makes this easier and provides a timestamp function that does the computation for you (and includes subseconds as a decimal component).

import dateutil.parser
    
time = "2020-02-25T00:02:43.000Z"
parsed_time = dateutil.parser.parse(time)
timestamp = int(parsed_time.timestamp() * 1000)
return str(timestamp)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.