简体   繁体   English

Python openpyxl 获取日期输出格式

[英]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我有一个无法更改的 excel 文件,我在其中使用 openpyxl 获取了一些信息,在这种情况下,我有一个具有此日期格式 MM/DD/YYYY 的单元格,我需要在 python 上的输出为:%d/%m/%是

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) (我是 Python 新手,也是编程新手)

datetime.strptime grabs a string and converts it into a datetime object. datetime.strptime一个字符串并将其转换为日期时间对象。 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' .在这种情况下,你告诉它你给它一个格式为'%d/%m/%Y'的字符串,而实际上它看起来你给它一个格式为'%Y-%m-%d %H:%M:%S'的字符串'%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.然后,您将拥有一个表示该日期/时间的 datetime 对象。 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:如果你想要一个你指定格式的新字符串,获取那个 datetime 对象并使用.strftime方法,将你的格式字符串传递给它,它会输出你想要的字符串:

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:这是你可以申请的iso:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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