Mar-17-2022, 09:49 AM
Mar-17-2022, 10:19 AM
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
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
Mar-17-2022, 11:26 AM
If you want to get back a valid ISO8601 string, then use
Using
Long version:
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/