简体   繁体   中英

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:

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 . The following code should showcase what I mean, not super Pythonic but it does the trick for your examples.

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM