天天看點

python calendar 時間處理類庫

#python中的calendar

import calendar

#傳回指定年的某月
def get_month(year, month):
    return calendar.month(year, month)

#傳回指定年的月曆
def get_calendar(year):
    return calendar.calendar(year)

#判斷某一年是否為閏年,如果是,傳回True,如果不是,則傳回False
def is_leap(year):
    return calendar.isleap(year)

#傳回某個月的weekday的第一天和這個月的所有天數
def get_month_range(year, month):
    return calendar.monthrange(year, month)

#傳回某個月以每一周為元素的序列
def get_month_calendar(year, month):
    return calendar.monthcalendar(year, month)

def main():
    year = 2013
    month = 8
    test_month = get_month(year, month)
    print(test_month)
    print('#' * 50)
    #print(get_calendar(year))
    print('{0}這一年是否為閏年?:{1}'.format(year, is_leap(year)))
    print(get_month_range(year, month))
    print(get_month_calendar(year, month))
    
if __name__ == '__main__':
    main()
           
最常用的time.time()傳回的是一個浮點數,機關為秒。但strftime處理的類型是time.struct_time,實際上是一個tuple。strptime和localtime都會傳回這個類型。

>>> import time
>>> t = time.time()
>>> t
1202872416.4920001
>>> type(t)
<type 'float'>
>>> t = time.localtime()
>>> t
(2008, 2, 13, 10, 56, 44, 2, 44, 0)
>>> type(t)
<type 'time.struct_time'>
>>> time.strftime('%Y-%m-%d', t)
'2008-02-13'
>>> time.strptime('2008-02-14', '%Y-%m-%d')
(2008, 2, 14, 0, 0, 0, 3, 45, -1)
           

轉載于:https://www.cnblogs.com/little-white/p/3673030.html