from datetime import datetime, date import time print("获取当天的日期戳:") print(time.time()) # 获取时间戳,包括小数点后七位 print(int(time.time())) # 只取整数部分 # print(time.sleep(3)) print(time.mktime(datetime.today().timetuple()), end="\n\n") print("获取当前的日期时间对象, date time 包括秒数的小数点后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.907182 1551603197 1551603197.0 获取当前的日期时间对象, date time 包括秒数的小数点后6位: 2019-03-03 16:53:17.907182 2019-03-03 16: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-03 2019-03-03 15:32:34 2019 获取当前的日期对象: 2019-03-03 16:53:17.907182 2019-03-03 16:53:17.907182 2019-03-03 时间戳和日期之间的相互转换: 2019-03-03 16: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=0) 1551598354.0 将日期对象转换为字符串 , 将字符串转换为日期对象: 2019-03-03 <class 'str'> 2019-03-03 00:00:00 <class 'datetime.datetime'>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。