python round()函数以及time模块datetime模块的使用、日期格式的转换
- Python round() 函数
- python time模块、datetime模块,格式相互转换
- strptime判断字符串是否为日期格式、判断生日日期格式是否正确
- datetime 模块之timedelta
Python round() 函数
round() 方法返回浮点数x的四舍五入值。
语法
round( x [, n] )
参数
1. x – 数字表达式。
2. n – 表示从小数点位数,其中 x 需要四舍五入,默认值为 0。
返回值
返回浮点数x的四舍五入值。
案例
#!/usr/bin/python3 print("round(12.56789) : ", round(12.56789)) print("round(12.123, 1) : ", round(12.123, 1)) print("round(34.561, 2) : ", round(34.561, 2)) print("round(111.000099, 3) : ", round(111.000099, 3)) print("round(111.000999, 3) : ", round(111.000999, 3)) print("round(-111.000099, 3) : ", round(-111.000099, 3)) print("round(-111.000999, 3) : ", round(-111.000999, 3))
输出结果:
round(12.56789) : 13
round(12.123, 1) : 12.1
round(34.561, 2) : 34.56
round(111.000099, 3) : 111.0
round(111.000999, 3) : 111.001
round(-111.000099, 3) : -111.0
round(-111.000999, 3) : -111.001
python time模块、datetime模块,格式相互转换
什么是时间元组?
很多Python函数用一个元组装起来的9组数字处理时间:
序号 | 字段 | 值 |
---|---|---|
0 | 4位数年 | 2008 |
1 | 月 | 1 到 12 |
2 | 日 | 1到31 |
3 | 小时 | 0到23 |
4 | 分钟 | 0到59 |
5 | 秒 | 0到61 (60或61 是闰秒) |
6 | 一周的第几日 | 0到6 (0是周一) |
7 | 一年的第几日 | 1到366 (儒略历) |
8 | 夏令时 | -1, 0, 1, -1是决定是否为夏令时的旗帜 |
上述也就是struct_time元组。这种结构具有如下属性:
序号 | 属性 | 值 |
---|---|---|
0 | tm_year | 2008 |
1 | tm_mon | 1 到 12 |
2 | tm_mday | 1 到 31 |
3 | tm_hour | 0 到 23 |
4 | tm_min | 0 到 59 |
5 | tm_sec | 0 到 61 (60或61 是闰秒) |
6 | tm_wday | 0到6 (0是周一) |
7 | tm_yday | 1 到 366(儒略历) |
8 | tm_isdst - | 1, 0, 1, -1是决定是否为夏令时的旗帜 |
import time import datetime # 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。 now_time = time.time() print('时间戳:', now_time) # 秒级时间戳 second_time = int(now_time) print('秒级时间戳:', second_time) # 毫秒级时间戳 print('毫秒级时间戳:', int(round(now_time * 1000))) # 毫秒级时间戳,基于lambda t = lambda: int(round(now_time * 1000)) print('毫秒级时间戳,基于lambda:', t()) # 微秒级时间戳 print('微秒级时间戳:', int(round(now_time * 1000*1000))) # now([tz]) 不指定时区,返回一个当前本地时间的datetime.datetime类的对象 # 指定时区,返回指定时区的时间 date_now = datetime.datetime.now() print('now:', date_now, type(date_now)) # today函数 返回一个当前本地时间的datetime.datetime类的对象。 date_today = datetime.datetime.today() print('today:', date_today, type(date_today)) # 日期时间格式化,datetime.datetime类的对象转换为指定格式的字符串 format_time_str = date_now.strftime('%Y-%m-%d %H:%M:%S') print('日期时间格式化:', format_time_str, type(format_time_str)) # strptime("时间字符串", format) 将格式时间字符串转换为datetime对象 format_time = datetime.datetime.strptime(format_time_str, '%Y-%m-%d %H:%M:%S') print('字符串日期时间格式化:', format_time, type(format_time)) # 将日期转为秒级时间戳 time_stamp = int(time.mktime(time.strptime(format_time_str, "%Y-%m-%d %H:%M:%S"))) print('将日期转为秒级时间戳', time_stamp) # 时间元祖或时间数组(9), struct_time now_struct = time.localtime(second_time) print('时间元祖:', now_struct) # 时间字符串转为时间元组 timeArray = time.strptime(format_time_str, "%Y-%m-%d %H:%M:%S") print('时间元祖:', timeArray) # 时间元祖可以调用其9个属性 # (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) tm_year = timeArray.tm_year print('tm_year:', tm_year) # 将秒级时间元祖转为字符串日期 date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(second_time)) print('秒级时间元祖转为字符串日期:', date_time, type(date_time)) # fromtimestamp(timestamp[,tz]) 给定一个时间戳,返回指定时区的datetime.datetime类的对象。不指定时区,返回本地时区的datetime类对象 date_now = datetime.datetime.fromtimestamp(time_stamp) print('秒级时间戳转日期:', date_now, type(date_now)) # Datetime类year、month、day、hour、minute、second属性 now_year = date_now.year print('当前年:', now_year) now_month = date_now.month print('当前月:', now_month) now_day = date_now.day print('当前日:', now_day) now_hour = date_now.hour print('当前时:', now_hour) now_minute = date_now.minute print('当前分:', now_minute) now_second = date_now.second print('当前秒:', now_second)
输出结果:
时间戳: 1554297769.87987
秒级时间戳: 1554297769
毫秒级时间戳: 1554297769880
毫秒级时间戳,基于lambda: 1554297769880
微秒级时间戳: 1554297769879870
now: 2019-04-03 21:22:49.879940 <class ‘datetime.datetime’>
today: 2019-04-03 21:22:49.879996 <class ‘datetime.datetime’>
日期时间格式化: 2019-04-03 21:22:49 <class ‘str’>
字符串日期时间格式化: 2019-04-03 21:22:49 <class ‘datetime.datetime’>
将日期转为秒级时间戳 1554297769
时间元祖: time.struct_time(tm_year=2019, tm_mon=4, tm_mday=3, tm_hour=21, tm_min=22, tm_sec=49, tm_wday=2, tm_yday=93, tm_isdst=0)
时间元祖: time.struct_time(tm_year=2019, tm_mon=4, tm_mday=3, tm_hour=21, tm_min=22, tm_sec=49, tm_wday=2, tm_yday=93, tm_isdst=-1)
2019
秒级时间元祖转为字符串日期: 2019-04-03 21:22:49 <class ‘str’>
秒级时间戳转日期: 2019-04-03 21:22:49 <class ‘datetime.datetime’>
当前年: 2019
当前月: 4
当前日: 3
当前时: 21
当前分: 22
当前秒: 49
strptime判断字符串是否为日期格式、判断生日日期格式是否正确
注意:
time.strptime(str_date, “%Y-%m-%d”),其本质是将日期字符串转换为时间元祖,如果格式不匹配就会报错,需要配合try使用
import time def is_valid_date(str_date): """判断是否是一个有效的日期字符串""" flag = False try: if ":" in str_date: time.strptime(str_date, "%Y-%m-%d %H:%M:%S") else: time.strptime(str_date, "%Y-%m-%d") flag = True except: pass try: if ":" in str_date: time.strptime(str_date, "%Y/%m/%d %H:%M:%S") else: time.strptime(str_date, "%Y/%m/%d") flag = True except: pass return flag def is_valid_date(str_date): """判断生日日期格式是否正确""" flag = False try: if "-" in str_date: time.strptime(str_date, "%Y-%m-%d") else: time.strptime(str_date, "%Y/%m/%d") flag = True except: pass return flag
datetime 模块之timedelta
timedalte 是datetime中的一个对象,该对象表示两个时间的差值
构造函数:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
其中参数都是可选,默认值为0
1 millisecond = 1000 microseconds
1 minute = 60 seconds
1 hour = 3600 seconds
1 week = 7 days
在构造函数中,参数值的范围如下:
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999
timedalte 有三个只读属性:
timedelta.min:负数最大时间差,相当于 timedelta(-999999999)。
timedelta.max:正数最大时间差,相当于 timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)。
timedelta.resolution:两个时间的最小差值 相当于 timedelta(microseconds=1)。
timedelta.total_seconds()方法:返回该时间差 以秒为单位的值
import time import datetime a = datetime.datetime.now() time.sleep(5) b = datetime.datetime.now() c = b - a print(c, type(c)) d = c.total_seconds() print(d, type(d)) a_str = a.strftime('%Y-%m-%d %H:%M:%S') a_time = datetime.datetime.strptime(a_str, '%Y-%m-%d %H:%M:%S') b_str = b.strftime('%Y-%m-%d %H:%M:%S') b_time = datetime.datetime.strptime(b_str, '%Y-%m-%d %H:%M:%S') c_timedelta = b_time - a_time print(c_timedelta, type(c_timedelta)) d_seconds = c_ti 27c7c medelta.total_seconds() print(d_seconds, type(d_seconds)) d_seconds_int = int(d_seconds) print(d_seconds_int, type(d_seconds_int))
输出结果:
0:00:05.001459 <class ‘datetime.timedelta’>
5.001459 <class ‘float’>
0:00:05 <class ‘datetime.timedelta’>
5.0 <class ‘float’>
5 <class ‘int’>
时间差:datetime.timedelta()
参数days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0
a = datetime.datetime.now() a_str = a.strftime('%Y-%m-%d %H:%M:%S') a_time = datetime.datetime.strptime(a_str, '%Y-%m-%d %H:%M:%S') print(a_time) one_day = datetime.timedelta(days=1) one_hour = datetime.timedelta(hours=1) print(one_day) print(one_hour) yestoday = a_time - one_day print(yestoday)
输出结果:
2019-04-03 22:14:16
1 day, 0:00:00
1:00:00
2019-04-02 22:14:16
注意:
拼接日期时有时需要判断当前的日期是否是1号,如果是需要做特殊处理,如下方代码
now_date = datetime.datetime.now() one_day = datetime.timedelta(days=1) yesterday_data = now_date - one_day if now_date.day == 1: next_date = datetime.datetime(yesterday_data.year, yesterday_data.month, yesterday_data.day, 17, 0, 0) else: next_date = datetime.datetime(now_date.year, now_date.month, yesterday_data.day, 17, 0, 0) next_date_str = '2019-04-03 23:03:03' next_date = datetime.datetime.strptime(next_date_str, '%Y-%m-%d %H:%M:%S') i_hour = datetime.timedelta(hours=1) next_date = next_date + i_hour print(next_date) # 2019-04-04 00:03:03 next_date_str = '2019-04-03 00:03:03' next_date = datetime.datetime.strptime(next_date_str, '%Y-%m-%d %H:%M:%S') i_hour = datetime.timedelta(hours=1) next_date = next_date - i_hour print(next_date) # 2019-04-02 23:03:03
- Python中time模块和datetime模块的常用操作以及几种常用时间格式间的转换
- python sys,os,time模块的使用(包括时间格式的各种转换)
- python 中time模块各种日期格式相互转化实例
- 使用Python内置的模块与函数进行不同进制的数的转换
- Python使用 time和datetime模块随意操作 时间
- python-包的使用-json与pickle模块-time与datetime模块-random模块
- 通过字符串格式去导入模块以及方法函数(getattr)——python3
- Python下time模块和datetime模块的使用
- python语言datetime模块将datetime对象转换为字符串格式strftime()方法具体指令
- Python中time,datetime模块的常见使用方法
- TO_DATE()函数:日期转换时使用RR格式的注意事项
- Python time、datetime、os、random、sys、hashlib、json、shutil、logging、paramiko、subprocess、ConfigParser、xml、shelve模块的使用
- Python中time模块与datetime模块在使用中的不同之处
- 使用Python内置的模块与函数进行不同进制的数的转换
- Python模块知识2:时间日期日历模块Time、Datetime、Calendar
- Python模块知识:时间日期日历模块Time、Datetime、Calendar
- Python中time模块与datetime模块在使用中的不同之处
- python时间模块time,时间戳,结构化时间,字符串时间,相互转换,datetime
- Python时间模块datetime、time、calendar的使用方法
- python的日期模块time,datetime