How do I generate a Python timestamp to my format?

lass9509

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'
kosciej16

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")

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how do i generate a python timestamp to a particular format

How do I generate a random timestamp in the next 5 days in Python?

How do I convert timestamp to datetime format in python for cosmos data?

How do I format a timestamp as GMT in Go?

How do I process this format of timestamp?

How do I format timestamp in array of objects?

How do I get this timestamp in the format I want, Oracle SQL

How do I convert an epoch timestamp to a human readable format on the cli?

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

How do i convert the simple system 24 hour format to Timestamp

How do I format an unix timestamp to RFC3339 - golang?

How do I convert timestamp to unix format with pyspark

How do I convert any Timestamp string to a single Format in Java

How do I format my flash drive?

How do I change the format of my SeekBar?

how do i format my usb stick

How to generate timestamp unix epoch format nodejs?

How can i change my response body timestamp format to unix timestamp?

How do I get my timeStamp variable to display the correct date?

How do I add the timestamp from Firestore to the my variable

How do I add a timestamp to my query results?

How do I extract only timestamp and date at my curl script?

How do I Generate Clones In Python?

How do I use DATE_FORMAT inside my MySQL statement in Python?

Excel to JSON using Python, how do I format this data to my needs?

Python: How do I output my float values with two digits after the decimal with new .format()?

How do I format my GET request to the Spotify Web API in Python?

How to format a timestamp in python to a readable format?

How do I make my Android app generate a random number?