How do I generate a Python timestamp to my format?

Question:

How can i generate a timestamp in python to this format? ‘2023-03-24T12:02:20.1273789+01:00’

formatted_timestamp = datetime.strptime(timestamp_string, '%Y-%m-%dT%H:%M:%S.%f%z').strftime(
                '%Y-%m-%d %H:%M:%S')

this returns

error: time data '2023-03-24T12:02:20.1273789+01:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
Asked By: lass9509

||

Answers:

So the problem with this timestamp_string is the number of microseconds digits – datetime expects it to be no more that 6.

To solve this, you can use dateutil

from dateutil import parser

s = "2023-03-24T12:02:20.1273789+01:00"
res = parser.parse(s)
formatted_timestamp = res.strftime("%Y-%m-%d %H:%M:%S")

Or format a bit earlier your timestamp_string:

from datetime import datetime
import re

timestamp_string = "2023-03-24T12:02:20.1273789+01:00"
clean_timestamp = re.sub(r"d+", "+", timestamp_string)

formatted_timestamp = datetime.strptime(clean_timestamp, "%Y-%m-%dT%H:%M:%S.%f%z").strftime("%Y-%m-%d %H:%M:%S")
Answered By: kosciej16
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.