简体   繁体   中英

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'

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM