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/