Python Forum

Full Version: Convert Date to another format
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I am looking to convert the date format of: 2022-03-16 to: 2022-03-16 06:00:00+00:00

How do I do that?

Thank you.
Could do it with datetime and using strftime() and strptime() Format Codes
I would suggest pendulum ,then it easier and special care has been taken to ensure timezones are handled correctly.
>>> import pendulum
>>> 
>>> d = '2022-03-16'
>>> date = pendulum.parse(d)
>>> date
DateTime(2022, 3, 16, 0, 0, 0, tzinfo=Timezone('UTC'))
>>> print(date)
2022-03-16T00:00:00+00:00
If you want to get back a valid ISO8601 string, then use datetime.datetime.fromisoformat and datetime.datetime.isoformat.
datetime.datetime.fromisoformat("2022-03-16").replace(hour=6).isoformat()
Output:
'2022-03-16T06:00:00'
To set the tzinfo, you could use the replace method of datetime object.
Using astimezone converts the naive datetime object to a timezone-aware datetime object.

Long version:
import datetime

new_dt = datetime.datetime.fromisoformat("2022-03-16").replace(hour=6, tzinfo=datetime.timezone.utc).isoformat()
print(new_dt)
Output:
2022-03-16T06:00:00+00:00
Cleaned up:
from datetime import datetime as DateTime
from datetime import timezone as TimeZone


def to_iso8601(iso_date: str, hour: int, tzinfo: TimeZone = TimeZone.utc) -> str:
    return (
        DateTime.fromisoformat(iso_date).replace(hour=hour, tzinfo=tzinfo).isoformat()
    )


print(to_iso8601("2020-01-01", 6))
Output:
2020-01-01T06:00:00+00:00
To get rid of the T, you can use str.replace
from datetime import datetime as DateTime
from datetime import timezone as TimeZone


def to_iso(iso_date: str, hour: int, tzinfo: TimeZone = TimeZone.utc) -> str:
    return (
        DateTime.fromisoformat(iso_date)
        .replace(hour=hour, tzinfo=tzinfo)
        .isoformat()
        .replace("T", " ")
    )


print(to_iso("2020-01-01", 6))
Output:
2020-01-01 06:00:00+00:00
For more of this complicated tasks, you should look into https://pypi.org/project/python-dateutil/