如何从日期时间获取日期 [英] how to get the date from datetime
问题描述
我有一个datetime对象,我想分别获取一个带日期的字符串和一个带时间的字符串。我希望theDate和theTime的值是字符串。
I have a datetime object and I'm trying to individually get a string with the date, and one with the time. I'd like the values for theDate and theTime to be strings.
theDate = myDatetime.date()
theTime = myDatetime.time()
类似这些内容。我尝试了str(datetime.date),但是它给了我一个内存中的参考,还有其他想法吗?预先感谢您的帮助。
Something along those lines. I tried str(datetime.date) but it gave me a reference in memory, any other ideas? Thanks in advance for any help.
推荐答案
使用 datetime.strftime()
方法上的datetime对象:
Use the datetime.strftime()
method on the datetime object:
theDate = myDatetime.strftime('%Y-%m-%d')
theTime = myDatetime.strftime('%H:%M:%S')
或者,将您的日期设为
和 time
对象转换为字符串作为其默认字符串表示形式:
Alternatively, turn your date
and time
objects into strings for their default string representations:
theDate = str(myDatetime.date())
theTime = str(myDatetime.time())
Demo:
>>> import datetime
>>> myDatetime = datetime.datetime.now()
>>> myDatetime.strftime('%Y-%m-%d')
'2013-06-19'
>>> myDatetime.strftime('%H:%M:%S')
'16:49:44'
>>> str(myDatetime.date())
'2013-06-19'
>>> str(myDatetime.time())
'16:49:44.447010'
默认 datetime.time
对象的字符串格式包括微秒部分。
The default string format for datetime.time
objects includes the microsecond component.
这篇关于如何从日期时间获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!