浅谈Python中用datetime包进行对时间的一些操作
作者:jingxian 时间:2022-09-27 09:32:14
1. 计算给出两个时间之间的时间差
import datetime as dt
# current time
cur_time = dt.datetime.today()
# one day
pre_time = dt.date(2016, 5, 20) # eg: 2016.5.20
delta = cur_time - pre_time
# if you want to get discrepancy in days
print delta.days
# if you want to get discrepancy in hours
print delta.hours
# and so on
2. 获取n天前的时间
cur_time = dt.now()
# previous n days
pre_time = dt.timedelta(days=n)
3. 将给定的时间精确到天或者其他单位
cur_time = dt.now()
# get day of current time
cur_day = cur_time.replace(hour=0, minute=0, second=0, mircrosecond=0)
4. 获取一连串的时间序列(返回list)
cur_time = dt.datetime.today()
datelist = [cur_time - dt.timedelta(days=x) for x in range(0, 100)]
或者
import pandas as pd
datelist = pd.date_range(pd.datetime.today(), periods=100).tolist()
5. 将时间字符串转化为datetime类型
date_formate = "%Y-%m-%d" # year-month-day
time = dt.strptime('2016-06-22', date_format)
6. 将时间类型转化为字符串类型
time_str = dt.strftime("%Y-%m-%d", dt.now()) # return like "2016-06-22"
标签:python,datetime,操作
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python装饰器相当于函数的调用方式
2021-05-13 13:39:03
pytorch载入预训练模型后,实现训练指定层
2022-01-22 12:40:35
Html中JS脚本执行顺序简单举例说明
2024-04-29 13:38:46
PHP禁止页面缓存的代码
2023-07-04 05:35:02
Python简洁优雅的推导式示例详解
2022-06-26 11:52:20
vue如何解决空格和空行报错的问题
2024-04-27 16:18:20
![](https://img.aspxhome.com/file/2023/1/132921_0s.png)
sql IDENTITY_INSERT对标识列的作用和使用
2024-01-20 16:05:04
![](https://img.aspxhome.com/file/2023/6/84356_0s.png)
在Pycharm中设置默认自动换行的方法
2022-09-10 04:29:00
python局域网ip扫描示例分享
2022-10-19 08:43:45
python中用ctypes模拟点击的实例讲解
2023-10-29 23:18:42
1500个绚丽主题 谷歌中国个人风格首页发布
2008-11-12 11:14:00
![](https://img.aspxhome.com/file/UploadPic/200811/12/1555350-62s.jpg)
Vision Transformer图像分类模型导论
2022-09-09 08:37:39
![](https://img.aspxhome.com/file/2023/1/134511_0s.png)
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
2022-04-24 02:59:36
![](https://img.aspxhome.com/file/2023/9/67419_0s.jpg)
Python进行区间取值案例讲解
2021-10-23 15:17:34
![](https://img.aspxhome.com/file/2023/5/70115_0s.png)
Python实现将Excel转换成为image的方法
2023-08-10 03:59:55
在Python的Flask框架下使用sqlalchemy库的简单教程
2021-02-23 23:58:40
Vue使用Echarts图表多次初始化报错问题的解决方法
2023-07-02 16:49:54
![](https://img.aspxhome.com/file/2023/4/139794_0s.png)
如何用VScode配置Python开发环境
2021-10-23 11:00:51
![](https://img.aspxhome.com/file/2023/5/115815_0s.gif)
MySQL创建用户与授权方法
2024-01-19 02:43:55
Python自动化办公之图片转PDF的实现
2023-07-24 21:29:07
![](https://img.aspxhome.com/file/2023/0/99620_0s.gif)