2011-11-07 66 views

回答

2

datetime.isoformat()

mydate = datetime.datetime.now() 
myxmldate = '<start>%s</start>' % mydate.isoformat() 
+1

投票這個,因爲它是F對於日期/時間使用ISO格式更安全:無論區域設置如何,它都可以正確解釋。爲了將來證明(Python 3)的代碼,最好說(2.6版本): 'myxmldate =' {}'.format(mydate.isoformat())' – shimofuri

0

嘗試既然你haveXML,是有意義的使用XML解析器。例如,lxml

import lxml.etree as ET 
import datetime 

mydate = datetime.datetime.now() 
doc = ET.fromstring('<start>%??</start>') 
for start in doc.xpath('//start'): 
    start.text = start.text.replace('%??',str(mydate)) 

print(ET.tostring(doc)) 

產量

<start>2011-11-07 12:28:58.883274</start> 
1

嘗試蘆葦for 2.6

>>> mydate.isoformat() 
'2002-03-11' 
>>> mydate.strftime("%d/%m/%y") 
'11/03/02' 
>>> mydate.strftime("%A %d. %B %Y") 
'Monday 11. March 2002' 

而對於第3版Using type-specific

>>> import datetime 
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58) 
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d) 
'2010-07-04 12:15:58'