2012-11-23 88 views
1

我的代碼是:如何將日期轉換爲Python中的時間格式?

import datetime 
tomorrow = datetime.date.today() + datetime.timedelta(days=1) 
print "Tomorrow date is" + str(tomorrow) 
tm_stme = datetime.time(0, 0, 0) 
tm_etime = datetime.time(23,59,59) 
tm_stdate = datetime.datetime.combine(tomorrow, tm_stme) 
tm_enddate = datetime.datetime.combine(tomorrow,tm_etime) 

print "tomorrow start date:" + str(tm_stdate) 
print "tomorrow end date:" + str(tm_enddate) 

tm_sdt_convert = time.mktime(time.strptime(tm_stdate, "%Y-%m-%d %H:%M:%S")) 
tm_tdt_convert = time.mktime(time.strptime(tm_enddate, "%Y-%m-%d %H:%M:%S")) 

和錯誤是:

[email protected]:~/Desktop$ python testing.py 
Tomorrow date is2012-11-24 
tomorrow start date:2012-11-24 00:00:00 
tomorrow end date:2012-11-24 23:59:59 
Traceback (most recent call last): 
    File "testing.py", line 17, in <module> 
    tm_sdt_convert = time.mktime(time.strptime(tm_stdate, "%Y-%m-%d %H:%M:%S")) 
    File "/usr/lib/python2.6/_strptime.py", line 454, in _strptime_time 
    return _strptime(data_string, format)[0] 
    File "/usr/lib/python2.6/_strptime.py", line 322, in _strptime 
    found = format_regex.match(data_string) 
TypeError: expected string or buffer 

我需要tm_sdt_convert變量的值。

回答

4

time.strptime採取一個格式化的字符串,其格式和rerurn包含日期時間信息的元組。 但是,您已經有了一個datetime對象,可以使用方法timetuple直接轉換爲元組。

所以正確的代碼應該是:

>>> tm_sdt_convert = time.mktime(tm_stdate.timetuple()) 
>>> tm_sdt_convert 
1353711600.0 

正確strptime用法:

>>> time.mktime(time.strptime(str(tm_stdate), "%Y-%m-%d %H:%M:%S")) 

有用當你只有一個包含字符串日期時間。

相關問題