[英]How do I get my Python date in the format that I want?
I'm reading a date from an Excel cell in Python (using .Value
on the cell)... the result that I get is: 我正在从Python中的Excel单元格读取日期(在单元格上使用
.Value
)...得到的结果是:
07/06/10 00:00:00
I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). 我以为这是一个字符串,因此尝试找出如何将其转换为所需的格式(在此示例中为“ yyyyMMdd”或“ 20100706”)。 However, after some playing around I realized that it is not being pulled as a string... Running type() on it returns
<type 'time'>
. 但是,经过一番游戏之后,我意识到它并没有作为字符串被拉出……在它上面运行type()返回
<type 'time'>
。
I then assumed that it was a Python time object, and tried using strftime
on it to convert it to a string... but that didn't work either. 然后,我以为这是一个Python时间对象,并尝试在其上使用
strftime
将其转换为字符串...但是那也不起作用。 It doesn't recognize the strftime
method on the value. 它无法识别该值的
strftime
方法。
Any idea on how to parse this properly and get the format I want? 关于如何正确解析并获取所需格式的任何想法吗? What am I doing wrong?
我究竟做错了什么? (And if this clearly contains a date as well as a time, why is Python automatically considering it a time object?)
(如果它明确包含日期和时间,为什么Python会自动将其视为时间对象?)
You can convert it to a time object like this: 您可以将其转换为时间对象,如下所示:
import time
time.strptime(str(thetime), '%m/%d/%y %H:%M:%S')
And then you should be able to manipulate it to your hearts content. 然后,您应该能够操纵它,使其满足您的内心需求。
HTH 高温超导
Have you tried str(time)
? 您尝试过
str(time)
吗? That should give it to you in a string and then you can play around with the formatting all you like. 这应该以字符串形式提供给您,然后您就可以尝试使用所有喜欢的格式了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.