time和datetime的具体使用
fromdatetimeimportdatetime,dateimporttimeprint("获取当天的日期戳:")print(time.time())#获取时间戳,包括小数点后七位print(int(time.time()))#只取整数部分#print(time.sleep(3))print(time.mktime(datetime.today().timetuple()),end="\n\n")print("获取当前的日期时间对象,datetime包括秒数的小数点后6位:")print(datetime.now())print(datetime.today(),end="\n\n")#time.struct_time(tm_year=2019,tm_mon=3,tm_mday=3,tm_hour=15,tm_min=23,tm_sec=36,tm_wday=6,tm_yday=62,tm_isdst=-1)print("构建日期时间的元组对象:")now_time_tuple=datetime.today().timetuple()print(now_time_tuple)print(now_time_tuple.tm_year,end="\n\n")#获取指定属性print("时间元组和时间戳相互转换:")print(time.localtime(time.time()))print(time.mktime(datetime.today().timetuple()),end="\n\n")#时间元组转换为时间戳print("构建指定日期的日期对象:")datetime_obj=datetime(year=2019,month=3,day=3,hour=15,minute=32,second=34)#microsecond属性不添加date_obj=date(year=2019,month=3,day=3)#microsecond属性不添加print(date_obj)print(datetime_obj)print(datetime_obj.year,end="\n\n")#获取日期的属性print("获取当前的日期对象:")print(datetime.now())print(datetime.fromtimestamp(time.time()))#将时间戳转换为日期print(date.today(),end="\n\n")print("时间戳和日期之间的相互转换:")timestamp=time.time()print(datetime.fromtimestamp(timestamp))#将时间戳转换为日期print(time.localtime(timestamp))print(datetime_obj.timestamp(),end="\n\n")#将日期对象转换为时间戳print("将日期对象转换为字符串,将字符串转换为日期对象:")datetime_now=datetime.now()datetime_str=datetime.strftime(datetime_now,"%Y-%m-%d")print(datetime_str)print(type(datetime_str))datetime_obj=datetime.strptime(datetime_str,"%Y-%m-%d")print(datetime_obj)print(type(datetime_obj))
结果如下:
获取当天的日期戳:1551603197.90718215516031971551603197.0获取当前的日期时间对象,datetime包括秒数的小数点后6位:2019-03-0316:53:17.9071822019-03-0316:53:17.907182构建日期时间的元组对象:time.struct_time(tm_year=2019,tm_mon=3,tm_mday=3,tm_hour=16,tm_min=53,tm_sec=17,tm_wday=6,tm_yday=62,tm_isdst=-1)2019时间元组和时间戳相互转换:time.struct_time(tm_year=2019,tm_mon=3,tm_mday=3,tm_hour=16,tm_min=53,tm_sec=17,tm_wday=6,tm_yday=62,tm_isdst=0)1551603197.0构建指定日期的日期对象:2019-03-032019-03-0315:32:342019获取当前的日期对象:2019-03-0316:53:17.9071822019-03-0316:53:17.9071822019-03-03时间戳和日期之间的相互转换:2019-03-0316:53:17.907182time.struct_time(tm_year=2019,tm_mon=3,tm_mday=3,tm_hour=16,tm_min=53,tm_sec=17,tm_wday=6,tm_yday=62,tm_isdst=0)1551598354.0将日期对象转换为字符串,将字符串转换为日期对象:2019-03-03<class'str'>2019-03-0300:00:00<class'datetime.datetime'>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。