时间偏移就是在指定时间往前推或者往后推一段时间,即加减一段时间之后的时间
python中主要有2种方式:一种是借助timedelta,另一种是pandas中的日期偏移量date offset
1 timedelta
1.1 时间偏移单位为周
1.1.1 往后推1周
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + timedelta(weeks=1))
result:
2007-05-19 18:53:32
1.1.2 往前推1周
date = datetime(2007, 5, 12, 18, 53, 32)
print(date - timedelta(weeks=1))
result:
2007-05-05 18:53:32
1.2 时间偏移单位为天
1.2.1 往后推1天
from datetime import timedelta, datetime
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + timedelta(days=1))
result:
2007-05-13 18:53:32
1.2.2 往前推1天
date = datetime(2007, 5, 12, 18, 53, 32)
print(date - timedelta(days=1))
result:
2007-05-11 18:53:32
1.3 时间偏移单位为小时
1.3.1 往后推1小时
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + timedelta(hours=1))
result:
2007-05-12 19:53:32
1.3.2 往前推1小时
date = datetime(2007, 5, 12, 18, 53, 32)
print(date - timedelta(hours=1))
result:
2007-05-12 17:53:32
1.4 时间偏移单位为分钟
1.4.1 往后推1分钟
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + timedelta(minutes=1))
result:
2007-05-12 18:54:32
1.4.2 往前推1分钟
date = datetime(2007, 5, 12, 18, 53, 32)
print(date - timedelta(minutes=1))
result:
2007-05-12 18:52:32
1.5 时间偏移单位为秒
1.5.1 往后推1秒
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + timedelta(seconds=1))
result:
2007-05-12 18:53:33
1.5.2 往前推1秒
date = datetime(2007, 5, 12, 18, 53, 32)
print(date - timedelta(seconds=1))
result:
2007-05-12 18:53:31
1.6 时间偏移单位为毫秒
1.6.1 往后推1毫秒
date = datetime(2007, 5, 12, 18, 53, 32, 987)
print(date + timedelta(milliseconds=1))
result:
2007-05-12 18:53:32.001987
1.6.2 往前推1毫秒
date = datetime(2007, 5, 12, 18, 53, 32, 987)
print(date - timedelta(milliseconds=1))
result:
2007-05-12 18:53:31.999987
1.7 时间偏移单位为微秒
1.7.1 往后推1微秒
date = datetime(2007, 5, 12, 18, 53, 32, 987)
print(date + timedelta(microseconds=1))
result:
2007-05-12 18:53:32.000988
1.7.2 往前推1微秒
date = datetime(2007, 5, 12, 18, 53, 32, 987)
print(date - timedelta(microseconds=1))
result:
2007-05-12 18:53:32.000986
2 date offset
from datetime import datetime
from pandas.tseries.offsets import Day
date = datetime(2007, 5, 12, 18, 53, 32, 987)
print(date + Day(1))
result:
2007-05-13 18:53:32.000987
2.1 时间偏移单位为天
2.1.1 往后推1天
date = datetime(2007, 5, 12, 18, 53, 32)
print(date + Day(1))
result:
2007-05-13 18:53:32
2.1.2 往前推1天
date = datetime(2007, 5, 12, 18, 53, 32,)
print(date - Day(1))
result:
2007-05-11 18:53:32
其他时间单位与timedelta差不多,单位为周、小时、分钟、秒时只要将Day相应的换为Week, Hour, Minute, Second就可以。在此不一一列举。
到此这篇关于pandas 时间偏移的实现的文章就介绍到这了,更多相关pandas 时间偏移内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!