Mariano
Mariano

Reputation: 455

How to convert UTC/extended format to datetime in Python

I want to convert datetime in %Y-%m-%d, so from Sat, 17 Apr 2021 16:17:00 +0100 to 17-04-2021

def convertDatetime(data):
    test_datetime = data
    data_new_format = datetime.datetime.strptime(test_datetime,'%- %Y %M %d')
    print(data_new_format)

convertDatetime("Sat, 17 Apr 2021 16:17:00 +0100")

but it say me: '-' is a bad directive in format '%- %Y %M %d'

Upvotes: 0

Views: 81

Answers (1)

BoarGules
BoarGules

Reputation: 16942

The format you specify '%- %Y %M %d' (1) contains an incorrect specifier - as the error says, and also (2) completely does not match the data you want to convert. The format you pass to strptime() must match the way the data looks, not the way you want it to look.

>>> data="Sat, 17 Apr 2021 16:17:00 +0100"
>>> format = "%a, %d %b %Y %H:%M:%S %z"
>>> datetime.datetime.strptime(data, format)
datetime.datetime(2021, 4, 17, 16, 17, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))

To reformat the datetime the way you want, you need a second call, to strftime():

>>> datetime.datetime.strptime(data, format).strftime("%Y-%m-%d")
'2021-04-17'

Upvotes: 3

Related Questions