最近作GPS定位項目,日期處理方面很是多.
python time和datetime模塊對日期處理方面總結 python
time模塊 spa
time.time() # 返回當前時間戳 """result 1382067918.718 """
time.strftime("%Y-%m-%d %X") # 或time.strftime("%Y-%m-%d %H:%M:%S") 返回當前格式化時間 """result '2013-10-18 11:47:02' """
time.strftime("%Y-%m-%d %X", time.localtime(1383185294.687)) """result '2013-10-31 10:08:14' """
time.mktime(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')) """result 1304584626.0 """
datetime模塊 code
d1 = datetime.datetime(2013, 06, 01) d2 = datetime.datetime(2013, 10, 18) delta = d2 - d1 # datetime.datetime對象日期差返回datetime.timedelta對象 """result datetime.timedelta(139) """2.返回如今的datetime.datetime
datetime.datetime.now() """result datetime.datetime(2013, 10, 18, 11, 57, 15, 250000) """3.datetime.datetime對象屬性
d = datetime.datetime.now() d.date() # datetime.date(2013, 10, 18) d.time() # datetime.time(12, 0, 54, 140000) d.weekday() # **返回星期幾 d.year d.month d.day d.hour d.minute d.second d.microsecond
d1 = datetime.datetime.now() d2 = d1 + datetime.timedelta(hours=10) # datetime.timedelta對象是把時間轉化爲能夠用於datetime.datetime對象加減的時間,而不是已是時間差了 print d2 """result datetime.datetime(2013, 10, 18, 22, 0, 54, 140000) """
datetime.datetime.strptime("2011-12-28 13:11:12", "%Y-%m-%d %X") """result datetime.datetime(2011, 12, 28, 13, 11, 12) """