Home > Net >  How to properly convert a datetime to a string?
How to properly convert a datetime to a string?

Time:10-13

Im trying to convert a datetime object to a string but it does not seem to give me the desired output.

from datetime import datetime

cur_time = datetime.now()
last_runtime = cur_time.strftime("%Y-%m-%dT%H:%M:%S.%f %Z") 
print(last_runtime)

My current output:

2021-10-13T09:09:27.824592 

My desired output:

2021-10-13T09:09:27.825 00:00

CodePudding user response:

You can use .astimezone() and small z on the format string:

from datetime import datetime

cur_time = datetime.now()
last_runtime = cur_time.astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z") 
last_runtime = "{0}:{1}".format(
  last_runtime[:-2],
  last_runtime[-2:]
)
print(last_runtime)

CodePudding user response:

You seem to expect an ISO 8601 compatible output. You can easily obtain that like

from datetime import datetime, timezone
t = datetime.now(timezone.utc)
t_iso = t.isoformat(timespec='milliseconds')
print(t_iso)
# 2021-10-13T07:32:41.527 00:00

The point is that you must set a time zone to get aware datetime, so that in the output string, the UTC offset is defined (e.g. 00:00 for UTC).

  • Related