Search code examples
pythontimeiso8601

How to minus time that received from API server and current time in Python


Kindly help below my query:

I got an estimated time from API server like below: 2019-09-25T20:11:23+08:00

it seems like iso 8601 standard with timezone.

I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.

import datetime

Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()

left_days = 
left_hour =
left_min =
left_sec =


Solution

  • Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7

    import datetime
    received = datetime.datetime.fromisoformat(Receved_time_frim_API)
    

    In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like

    >>> date, timezone = Receved_time_frim_API.split("+")
    >>> tz_hours, tz_minutes = timezone.split(":")
    >>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
    >>> date -= datetime.timedelta(hours=int(tz_hours))
    >>> date -= datetime.timedelta(minutes=int(tz_minutes))
    

    Note that this will work only in case of positive timezones

    To substract two datetime objects use

    td = date - Current_time
    left_days = td.days
    left_hour = td.seconds // 3600
    left_min = (td.seconds//60)%60
    left_sec = td.seconds % 60