i have an excel file that i cant change, where im getting some info with openpyxl, on this case i have a cell with this DATE format MM/DD/YYYY i need the output on python to be: %d/%m/%Y
Ive tried this :
ETD3 = sheet['F28'].value
ETD2 = str(ETD3)
ETD = datetime.strptime(ETD2,'%d/%m/%Y')
I get this error :
Traceback (most recent call last):
File "C:\Users\xxxx\eclipse-workspace\TEst\RunFaster.py", line 102, in <module>
ETD = datetime.strptime(ETD2,'%d/%m/%Y')
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\xxxx\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2021-10-15 00:00:00' does not match format '%d/%m/%Y'
How can i make this work correctly? (im new in python and also on programming)
datetime.strptime
grabs a string and converts it into a datetime object. The format you give it tells it how to interpret the string it's grabbing. In this case, you're telling it that you're giving it a string formatted like '%d/%m/%Y'
, when in fact it appears you're giving it a string formatted like '%Y-%m-%d %H:%M:%S'
. This is the format string you should give it. You will then have a datetime object representing that date/time. If you want to have a new string in the format you indicated, take that datetime object and use the .strftime
method, passing your format string to it, and it will output the string how you want it:
ETD3 = sheet['F28'].value
ETD2 = str(ETD3)
DT = datetime.strptime(ETD2,'%Y-%m-%d %H:%M:%S')
ETD = DT.strftime('%d/%m/%Y')
This is iso you can apply:
from datetime import datetime
ETD = datetime.fromisoformat('2021-10-15 00:00:00'))
print(f"{ETD.day}/{ETD.month}/{ETD.year}")
Output:
15/10/2021
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.