[英]How do I convert a time string like "last Sunday" or "Next Monday" into datetime format in python
I am trying to find a way to convert a time string like "last Sunday" or "Next Monday" into DateTime format using python 3. I tried out using the follwoing:我正在尝试找到一种使用 python 3 将“上周日”或“下周一”之类的时间字符串转换为 DateTime 格式的方法。我尝试使用以下方法:
x = datetime.strptime("Sunday", "%A")
but it gave a output like this:但它给出了这样的输出:
1900-01-01 00:00:00
I want to know how to get the Date in relation to the current Date!我想知道如何获取与当前日期相关的日期!
Thank you :)谢谢 :)
My suggestion: Build up a helper index to find out how many days ahead or before the day is and then work with timedelta
.我的建议:建立一个辅助索引以找出一天之前或之前的天数,然后使用
timedelta
。 The following code should showcase what I mean, not super Pythonic but it does the trick for your examples.下面的代码应该展示我的意思,不是超级 Pythonic,但它可以为您的示例提供技巧。
from datetime import datetime
from datetime import timedelta
now = datetime.now()
nowDayString = now.strftime("%A")
days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]
def buildLut():
floatingDays = [""]*8
for idx, day in enumerate(days):
if day == nowDayString:
floatingDays[0] = nowDayString
floatingDays[7] = nowDayString
for i, j in zip(range(idx+1, len(days)), range(1, len(days))):
floatingDays[j] = days[i]
for i in range(idx):
floatingDays[7-(idx-i)] = days[i]
return floatingDays
def findme(s):
td = timedelta()
dayToLookFor = s.split(" ")[1]
if "last" in s.lower():
td = timedelta(days=-(7 - floatingDays.index(dayToLookFor)))
elif "next" in s.lower():
td = timedelta(days=floatingDays.index(dayToLookFor))
return now + td
floatingDays = buildLut()
print(floatingDays)
print(findme("last Sunday"))
print(findme("Next Monday"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.