Home > Software engineering >  How can I create a python datetime with trimmed milliseconds (3 digits) AND utc offset?
How can I create a python datetime with trimmed milliseconds (3 digits) AND utc offset?

Time:06-28

I'd like to get date with 3 digit milliseconds and UTC offset, for example:

'2022-06-27T14:51:23.230 00:00'

I have the following code:

now = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d-%H%M%S%f%z')
created = datetime.datetime.strptime(now,'%Y%m%d-%H%M%S%f%z').isoformat()

The issue is that I am getting the following format:

'2022-06-27T14:51:23.230061 00:00'

Obviously I cannot cut the last 3 digits using [:-3] as I will cut the utc offset and will end up with:

'2022-06-27T14:51:23.230061 00'

Is there any other way to tell datetime to return only 3 digits for milliseconds or trim it in any other way?

CodePudding user response:

You need to set timespec to 'milliseconds' when calling datetime.isoformat():

from datetime import datetime, timezone

created = datetime.now(timezone.utc).isoformat(timespec='milliseconds')

Output:

2022-06-27T14:51:23.230 00:00

You can help my country, check my profile info.

  • Related