The original date is : 2020-01-31 00:00:00
Last business day : 2020-01-30 00:00:00
方法二:使用 max() + %运算符+time delta()
以类似的方式执行任务,唯一的区别是计算差异变化的方法,以获得 max()和%运算符。
Python 3
# Python3 code to demonstrate working of
# Last business day
# using max() + % operator + timedelta()
from datetime import datetime, timedelta
# initializing dates
test_date = datetime(2020, 1, 31)
# printing original date
print("The original date is : " + str(test_date))
# getting difference
# using max() to get differences
diff = max(1, (test_date.weekday() + 6) % 7 - 3)
# subtracting diff
res = test_date - timedelta(days=diff)
# printing result
print("Last business day : " + str(res))
*输出:*
The original date is : 2020-01-31 00:00:00
Last business day : 2020-01-30 00:00:00
*方法 3:使用*PD . tseries . offset . business day(n)
在这种情况下,我们创建一个 1 天的工作日偏移量,并从初始化日期中减去。这将根据需要返回前一个工作日。
Python 3
# Python3 code to demonstrate working of
# Last business day
# using pd.tseries.offsets.BusinessDay(n)
import pandas as pd
from datetime import datetime
# initializing dates
test_date = datetime(2020, 2, 3)
# printing original date
print("The original date is : " + str(test_date))
# Creating Timestamp
ts = pd.Timestamp(str(test_date))
# Create an offset of 1 Business days
offset = pd.tseries.offsets.BusinessDay(n=1)
# getting result by subtracting offset
res = test_date - offset
# printing result
print("Last business day : " + str(res))
*输出:*
The original date is : 2020-02-03 00:00:00
Last business day : 2020-01-31 00:00:00
版权属于:月萌API www.moonapi.com,转载请注明出处
本文链接:https://moonapi.com/news/6043.html