pythondatetimetimetimestamp

How do I import this timestamp, and then get days since the timestamp?


I am receiving a timestamp as a string in this format 2024-09-27T04:58:04.894614Z

I've done a lot of playing and reading around using import datetime, converting to datetime objects

e.g. timestamp = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')

But datetime seems extremely confusing to use.

I am current using

from datetime import datetime, date, time, timedelta which cannot be changed.

How can I get the number of days since the imported timestamp please?


Solution

  • Keep it simple,


    from datetime import datetime
    
    timestamp = "2024-09-21T04:58:04.894614Z"
    timestamp_dt = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')
    now = datetime.now()
    difference = now - timestamp_dt
    days_since = difference.days
    

    You can also use fromisoformat, as suggested by Mark Tolonen:

    timestamp_dt = datetime.fromisoformat(timestamp.rstrip("Z"))
    

    Note that the date format is wrong also, the correct one should be:

    %Y-%m-%dT%H:%M:%S.%fZ
    

    Full example