Convert date string to ISOFormat with "T" and "Z"

0

With a date in string in 01/01/2018 13:00:40 format, how could I convert it to iso format using "T" and "Z" , example: 2018-01-01T13:00:40Z

I was able to do this as follows;

datetime.strftime(
    datetime.strptime("01/01/2018 13:00:40", "%d/%m/%Y %H:%M:%S"),
    "%Y-%m-%dT%H:%M:%SZ"
)

But I do not think it's the best way, is there any other method for this conversion?

    
asked by anonymous 04.09.2018 / 19:02

1 answer

2

To define an object of type date, there is not much to do. Because your date is not in any ISO format, you need to set it manually, just like you did.

date = datetime.strptime('15/03/2018 13:00:40', '%d/%m/%Y %H:%M:%S')

However, the desired format is part of ISO and already has native methods that deal with it:

print( date.isoformat() )  # 2018-01-01T13:00:40

So just because you can use isoformat() instead of strftime already simplifies your code.

If the entry is always in Brasilia time, you can set the timezone by default by replacing the tzinfo field of the date object:

tzone = timezone(timedelta(hours=-3))
date = datetime.strptime('15/03/2018 13:00:40', '%d/%m/%Y %H:%M:%S')
date = date.replace(tzinfo=tzone)

print( date.isoformat() )  # 2018-03-15T13:00:40-03:00
    
04.09.2018 / 19:18