Home > Mobile >  How do I get the day for a given date with a 5 digit year?
How do I get the day for a given date with a 5 digit year?

Time:08-05

I found this code on the web that uses datetime:

import datetime
import calendar
 
def findDay(date):
    born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
    return (calendar.day_name[born])

print(findDay("01 01 2022"))

And it works perfectly fine with that argument to findDay(). However, it doesn't accept a 5 digit year (like 22022). Is there any way I can modify this code to do so? Here is the exception it currently throws for findDay("01 01 20200"):

Traceback (most recent call last):
  File "c:\Users\\OneDrive\Documents\Python\Untitled-1.py", line 8, in <module>
    print(findDay("01 01 20200"))
  File "c:\Users\\OneDrive\Documents\Python\Untitled-1.py", line 5, in findDay
    born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
  File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %

CodePudding user response:

The "datetime" package supports years between 1 and 9999.

You can use the astropy package (link) and subtract several weeks from your date to be between 0 and 9999, and then covert it to datetime object and call the weekday method.

like this:

import calendar
import re
import astropy.time as astropy_time


def findDay(date):
    timeformat = re.compile(r"(?P<day>\d{2}) (?P<month>\d{2}) (?P<year>\d{5}|\d{4})")
    match = timeformat.fullmatch(date)
    assert match and len(match.group("year")) in {4, 5}

    year = int(match.group("year"))
    month = int(match.group("month"))
    day = int(match.group("day"))

    time = astropy_time.Time({"year": year, "month": month, "day": day}, scale="utc")

    if year > 9999:
        year_delta = year - 9999
        week_delta = year_delta * 53
        week_sec = 7 * 24 * 60 * 60
        sec_delta = week_delta * week_sec

        time = time - astropy_time.TimeDelta(sec_delta, format="sec")

    born = time.datetime.weekday()
    return calendar.day_name[born]


print(findDay("01 01 22022"))

CodePudding user response:

strptime is simply not capable of that. You need to implement your own string parser if you want that.

More likely in this slightly strange use case, you'll rather construct the datetime object manually, specifying the year as integer keyword argument. I recommend lecture of the datetime python module documentation! They wrote that for good reason :)

  • Related