Jatin Mehrotra
Jatin Mehrotra

Reputation: 11492

Format string date time into desired format in python

I have a variable which is of type string in timestamp format Fri, 19 Mar 2021 06:15:55 +0000

Used https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior to format but it throws ValueError: time data 'Fri, 19 Mar 2021 06:15:55 +0000' does not match format '%a, %d %b %Y %H:%M:%S.%f'

my code for changing format

pub_date=datetime.datetime.strptime(i.published, '%a, %d %b %Y %H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')

Upvotes: 0

Views: 105

Answers (1)

E. Ducateme
E. Ducateme

Reputation: 4238

Try this:

pub_date=datetime.datetime.strptime(i.published, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S')

That last formatting code should not require a period and it should be a %z instead of %f

What is the difference between the codes?

%f Used when microsecond are represented as a decimal number, zero-padded on the left. For example: 000000, 000001, …, 999999

%z Used when the UTC offset is represented in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive). For example: +0000, -0400, +1030, +063415, -030712.345216

References:

datetime module in general: https://docs.python.org/3/library/datetime.html

Details about the format specification: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Upvotes: 1

Related Questions