Skip to content
Advertisement

Python openpyxl get date output format

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:Usersxxxxeclipse-workspaceTEstRunFaster.py", line 102, in <module>
    ETD = datetime.strptime(ETD2,'%d/%m/%Y')
  File "C:UsersxxxxAppDataLocalProgramsPythonPython310lib_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:UsersxxxxAppDataLocalProgramsPythonPython310lib_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)

Advertisement

Answer

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')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement