![](/img/trans.png)
[英]How do you convert a time.struct_time object into a datetime object?
[英]How do I convert a datetime.date object into a time.struct_time object?
我有一個python腳本,我需要比較兩個日期。 我有一個列表日期作為time.struct_time對象,我需要與一些datetime.date對象進行比較。
如何將datetime.date對象轉換為time.struct_time對象? 或者我可以直接使用它們進行比較嗎?
嘗試使用date.timetuple()
。 從Python文檔:
返回
time.struct_time
例如time.localtime()
返回的。 小時,分鍾和秒為0,DST標志為-1。d.timetuple()
相當於time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
,其中yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1
是當前年份中從1月1日開始的1的日期編號。
將日期對象轉換為time.struct_time對象的示例:
#### Import the necessary modules
>>> dt = date(2008, 11, 10)
>>> time_tuple = dt.timetuple()
>>> print repr(time_tuple)
'time.struct_time(tm_year=2008, tm_mon=11, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=0, tm_yday=315, tm_isdst=-1)'
有關更多示例,請參閱此鏈接: http : //www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/
請參閱時間Python模塊的文檔,它指示您可以使用calendar.timegm或time.mktime將time.struct_time對象轉換為自紀元以來的秒數(您使用的函數取決於您的struct_time是在時區還是在UTC時間)。 然后,您可以在另一個對象上使用datetime.datetime.time ,並在紀元以來的秒數內進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.