Home > database >  Dynamically formatting dates and times fetched from an API in iso format
Dynamically formatting dates and times fetched from an API in iso format

Time:07-28

I am fetching data from an API that comes in iso formated strings, for ex - example 2022-07-27T00:00:00.0000000 01:00

end_date=item['RunDate'] 
start_time=portion['StartTimeWTT'] 

I am trying to format the date to look like: yyyy-mm-dd and time hh:mm:ss I have tried different solutions but none of them works

end_date1=train['RunDate']
end_date=datetime.date().strftime(end_date1,'%Y-%M-%d')

or datetime.fromisoformat

I would be grateful for any suggestions.

CodePudding user response:

For me, the easiest way to handle date strings is by using the dateutil library. For example in your cited case:

from dateutil import parser
from dateutil.utils import default_tzinfo
from dateutil.tz import tzoffset
tx = '2022-07-27T00:00:00.0000000 01:00'
tz_data = tzoffset("EST", 0)
print(default_tzinfo(parser.parse(tx) , tz_data))

yields

2022-07-27 00:00:00 01:00     
  • Related