简体   繁体   English

如何以所需的格式获取Python日期?

[英]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.

相关问题 如何在python中获取当前日期时间的字符串格式? - How do I get a string format of the current date time, in python? 在python中,如何使用pandas将字符串日期列转换为日期格式? - In python, how do I convert my string date column to date format using pandas? 如何在python中获取代码以执行我想要的操作? - how do I get my code in python to do what I want? 如何比较 python 中的日期? 我有月份日期年份格式并想与当前日期(7 天内)进行比较 - How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days) 我有一个格式为“12/Sep/21”的日期字符串。 我想将格式更改为“2021-09-12”。 我怎样才能在 Python 中做到这一点? - I have a date string with the format '12/Sep/21'. I want to change the format to '2021-09-12'. How can I do this in Python? 如何在Python中的MySQL语句中使用DATE_FORMAT? - How do I use DATE_FORMAT inside my MySQL statement in Python? 我想以以下格式获取 python 的列表 - I want to get the list of python in the below format 使用python如何按季度获取日期 - With python How do i get the date by quarter 如何将我的日期转换为稍微不同的格式 - How do I convert my date into a slightly different format 我想在 python 中获取用户的出生日期 - I want to get the user date of birth in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM