如何在python中将日期转换为时间格式?

时间:2012-11-23 11:57:56

标签: 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"))

错误是:

administrator@Ashok-Dev:~/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变量的值。

1 个答案:

答案 0 :(得分:4)

time.strptime采用格式化字符串,其格式并重新生成包含日期时间信息的元组。 但是你已经有一个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"))

只有包含日期​​时间的字符串时才有用。