python的time、datetime和calendar

datetime模块主要是用来表示日期的,就是我们常说的年月日时分秒,calendar模块主要是用来表示年月日,是星期几之类的信息,time模块主要侧重点在时分秒,从功能简单来看,我们可以认为三者是一个互补的关系。我们可以依据不同的使用目的选用合适的模块。


1.time.time() 返回当前时间戳;

print(time.time())#输出:1525410174.8452504


2.time.ctime() 返回这种格式的时间字符'Wed Jun 8 15:27:48 2016',显示当前时间;

print(time.ctime())#输出:Fri May  4 13:02:54 2018


3.time.gmtime 将时间戳转换成struct_time格式,此显示的是格林威治0时区的时间;

print(time.gmtime())#输出:time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=5, tm_min=2, tm_sec=54, tm_wday=4, tm_yday=124, tm_isdst=0)

4.time.localtime 将当前系统时间戳转化为struct_time格式 ;

print(time.localtime())#输出:time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=13, tm_min=2, tm_sec=54, tm_wday=4, tm_yday=124, tm_isdst=0)


注意:struct_time元组中元素主要包括tm_year(年)、tm_mon(月)、tm_mday(日)、tm_hour(时)、tm_min(分)、tm_sec(秒)、tm_wday(weekday0 - 6(0表示
周日))、tm_yday(一年中的第几天1 - 366)、tm_isdst(是否是夏令时)

5.time.mktime 将struct_time格式转回成时间戳;

print(time.mktime(time.localtime()))#输出:1525410174.0


6.time.strftime 将struct_time格式转成指定的字符串格式;

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))#输出:2018-05-04 13:02:54


7.time.strptime 将自定义时间格式的字符串转换为struct_time格式;

print(time.strptime("2018-05-04","%Y-%m-%d"))#输出:time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4,tm_yday=124, tm_isdst=-1)


8.time.sleep 暂停时间。

print(time.sleep(2))


注:time. gmtime()和time.localtime()这两个函数如果调用时不传参数,它们内部会调用time.time(),并用返回的秒数做转换。

******************************************************************************************

import datetime

1.datetime.datetime.today() 默认返回当前日期和时间的对象,也可以自定义日期和时间;

print(datetime.datetime.today())#输出:2018-05-04 13:15:57.819725
print(datetime.datetime(2018,5,4,0,0,0))#注意此处表示日期只能是实际月份,不能带0
#输出:2018-05-04 00:00:00


2.datetime.datetime.now() 返回当前时间;

print(datetime.datetime.now())#输出:2018-05-04 13:15:57.819725


3.datetime.strftime(format)  #自定义格式化时间;

nowtime =datetime.datetime.now()
print(nowtime.strftime("%I:%M:%S %p %d/%m/%Y"))#自定义格式化时间
#输出:01:15:57 PM 04/05/2018


4.datetime.datetime.timple() 将时间转换为struct_time 格式;

print(nowtime.timetuple())#输出:time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=13, tm_min=15, tm_sec=57, tm_wday=4, tm_yday=124, tm_isdst=-1)


5.datetime的时间运算:

nowtime =datetime.datetime.now()#当前时间是:2018-05-04 13:15:57.819725
print(nowtime-datetime.timedelta(days=1))#输出:2018-05-03 13:15:57.819725
print(nowtime-datetime.timedelta(hours=3))#输出:2018-05-04 10:15:57.819725



*****************************************************************************************

import calendar

1.返回日历

print(calendar.month(2018,5))
#输出:
      May 2018
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

猜你喜欢

转载自www.cnblogs.com/Downtime/p/8990230.html