0

I get two type of timestamp (one with millisecond and another one without it)

'endtime': '2020-09-09T05:46:41.620Z'

'starttime': '2020-09-08T18:20:57Z'

I have to specify the format to convert it into datetime

timestampstart = pd.to_datetime(starttime, format="%Y-%m-%dT%H:%M:%S%fZ")

is there a way to generalize "format" in this line, because if my time has millisecond, the code will crash.

how can rewrite this to always ignore millisecond without getting my code crashed?

phoenix
  • 328
  • 2
  • 12
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Sep 09 '20 at 06:54

1 Answers1

1

Both formats are ISO8601 compliant. You can parse the timestamps conveniently using datetime.fromisoformat after you replace the 'Z' character (which denotes UTC) with '+00:00' (also UTC). You can find this method also here.

from datetime import datetime

endtime = '2020-09-09T05:46:41.620Z'
starttime = '2020-09-08T18:20:57Z'

for t in (endtime, starttime):
    print(repr(datetime.fromisoformat(t.replace('Z', '+00:00'))))
    
# datetime.datetime(2020, 9, 9, 5, 46, 41, 620000, tzinfo=datetime.timezone.utc)
# datetime.datetime(2020, 9, 8, 18, 20, 57, tzinfo=datetime.timezone.utc)

To set all microseconds to zero you can write

# setting microseconds to zero:
for t in (endtime, starttime):
    print(repr(datetime.fromisoformat(t.replace('Z', '+00:00')).replace(microsecond=0)))
    
# datetime.datetime(2020, 9, 9, 5, 46, 41, tzinfo=datetime.timezone.utc)
# datetime.datetime(2020, 9, 8, 18, 20, 57, tzinfo=datetime.timezone.utc)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • is there a way to remove milliseconds from my question, if milliseconds are there in either starttime or endtime? ignore if milliseconds are not there? – phoenix Sep 09 '20 at 07:03
  • @phoenix: I think best would be to `.replace(microsecond=0)`. You can do that in any case; the operation won't cost you much and won't hurt in case microseconds are already zero. – FObersteiner Sep 09 '20 at 07:11