0

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()

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.

4

1 回答 1

3

Use the datetime.strftime() method on the datetime object:

theDate = myDatetime.strftime('%Y-%m-%d')
theTime = myDatetime.strftime('%H:%M:%S')

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'

The default string format for datetime.time objects includes the microsecond component.

于 2013-06-19T15:02:03.923 回答