Question

I am somehow stuck in logical thinking.

I am going to compare date for this two states:

  1. Summer semester (beginns on 16.04 - ends on 14.10)
  2. Winter semester (beginns on 15.10 - ends on 15.04)

all including vacations

how do i check what semester this month/day in?

current_month = datetime.datetime.now().month
current_year = datetime.datetime.now().year
current_day = datetime.datetime.now().day

if current_month>=10 and current_day>=15:
   #winter semester

but i am somehow doing it too chaos. is there any python lib for date comparison for my problem?

Was it helpful?

Solution

You could generate the summer dates:

current = datetime.date.today()
summer = current.replace(month=4, day=16), current.replace(month=10, day=14)

if summer[0] <= current <= summer[1]:
    # summer semester
else:
    # winter semester

This use a datetime.date() object instead of a datetime.datetime(), as the time portion is irrelevant here. The date.replace() calls make sure we reuse the current year.

This all assumes, of course, that summer semester starts and ends on the same dates each year.

Demo:

>>> import datetime
>>> current = datetime.date.today()
>>> current
datetime.date(2013, 9, 3)
>>> summer = current.replace(month=4, day=16), current.replace(month=10, day=14)
>>> summer[0] <= current <= summer[1]:
True

OTHER TIPS

One approach is to create a lookup table (this is often a good idea when you have many disjointed time intervals, but each is a discrete size, like a day).

Another would be to test whether it is summer - after April 16 and before October 15. If it's not summer, it's winter. Works great when you just have two intervals - breaks down (messy code) if you have many more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top