Calendar Functions in Python | Set 2 (monthrange (), prcal (), weekday () …)

File handling | Python Methods and Functions | weekday

1. monthrange (year, month) : — This function returns two integers, first, the number of the day of the week at the beginning (0 as Monday), and second, the number of days in the month .

2. prcal (year, w, l, c) : — This function also prints the calendar of a specific year, but does not require a print operation.

# Python code to demonstrate how it works
# monthrange () and prcal ()

 
# import of the calendar module for calendar operations

import calendar

 
# using monthrange () to print the weekday and
# month number

print ( "The start week number and no. of days of month:" , end = "")

print (calendar.monthrange ( 2008 , 2 ))

 
# using prcal () to print the 1997 calendar

print ( " The calendar of 1997 is: " )

calendar.prcal ( 1997 , 2 , 1 , 6 )

Exit:

 The start week number and no. of days of month: (4, 29) The calendar of 1997 is: 1997 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 

3. prmonth (year, month, w, l) : — This function also prints the month of a specific year, but does not require a "print" operation.

4. setfirstweekday (num) : — This function sets the starting number of the day of the week.

# Python code to demonstrate how it works
# prmonth () and setfirstweekday ()

 
# import of the calendar module for calendar operations

import calendar

 
# using prmonth () to print the 1997 calendar

print ( "The 4th month of 1997 is:" )

calendar.prmonth ( 1997 , 4 , 2 , 1 )

 

 
# using setfirstweekday () to set the first week day number

calendar.setfirstweekday ( 4 )

 

print ( " " )

 
# using firstweekday () to check the changed day

print ( "The new week day number is:" , end = "")

print (calendar.firstweekday ())

Output:

 The 4th month of 1997 is: April 1997 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 The new week day number is: 4 

5. weekday (year, month, date) : — this function returns weekday number (0 — Monday) of the date specified in its arguments.

# Python code to demonstrate how it works
# weekday ()

 
# import of the calendar module for calendar operations

import calendar

 
# using the day of the week () to display the day number of the date

print ( "The day number of 25 April 1997 is: " , end = " ")

print (calend ar.weekday ( 1997 , 4 , 25 ))

Output:

 The day number of 25 April 1997 is: 4 

This article is courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





Calendar Functions in Python | Set 2 (monthrange (), prcal (), weekday () ...): StackOverflow Questions

Answer #1

If you"d like to have the date in English:

from datetime import date
import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()]  #"Wednesday"

Answer #2

date and datetime objects (and time as well) support a mini-language to specify output, and there are two ways to access it:

So your example could look like:

  • dt.strftime("The date is %b %d, %Y")
  • "The date is {:%b %d, %Y}".format(dt)
  • f"The date is {dt:%b %d, %Y}"

In all three cases the output is:

The date is Feb 23, 2012

For completeness" sake: you can also directly access the attributes of the object, but then you only get the numbers:

"The date is %s/%s/%s" % (dt.month, dt.day, dt.year)
# The date is 02/23/2012

The time taken to learn the mini-language is worth it.


For reference, here are the codes used in the mini-language:

  • %a Weekday as locale‚Äôs abbreviated name.
  • %A Weekday as locale‚Äôs full name.
  • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
  • %d Day of the month as a zero-padded decimal number.
  • %b Month as locale‚Äôs abbreviated name.
  • %B Month as locale‚Äôs full name.
  • %m Month as a zero-padded decimal number. 01, ..., 12
  • %y Year without century as a zero-padded decimal number. 00, ..., 99
  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %H Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23
  • %I Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12
  • %p Locale‚Äôs equivalent of either AM or PM.
  • %M Minute as a zero-padded decimal number. 00, ..., 59
  • %S Second as a zero-padded decimal number. 00, ..., 59
  • %f Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999
  • %z UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030
  • %Z Time zone name (empty if naive), UTC, EST, CST
  • %j Day of the year as a zero-padded decimal number. 001, ..., 366
  • %U Week number of the year (Sunday is the first) as a zero padded decimal number.
  • %W Week number of the year (Monday is first) as a decimal number.
  • %c Locale‚Äôs appropriate date and time representation.
  • %x Locale‚Äôs appropriate date representation.
  • %X Locale‚Äôs appropriate time representation.
  • %% A literal "%" character.

Answer #3

Use:

from datetime import datetime

current_month = datetime.now().strftime("%m") // 02 //This is 0 padded
current_month_text = datetime.now().strftime("%h") // Feb
current_month_text = datetime.now().strftime("%B") // February

current_day = datetime.now().strftime("%d")   // 23 //This is also padded
current_day_text = datetime.now().strftime("%a")  // Fri
current_day_full_text = datetime.now().strftime("%A")  // Friday

current_weekday_day_of_today = datetime.now().strftime("%w") //5  Where 0 is Sunday and 6 is Saturday.

current_year_full = datetime.now().strftime("%Y")  // 2018
current_year_short = datetime.now().strftime("%y")  // 18 without century

current_second= datetime.now().strftime("%S") //53
current_minute = datetime.now().strftime("%M") //38
current_hour = datetime.now().strftime("%H") //16 like 4pm
current_hour = datetime.now().strftime("%I") // 04 pm

current_hour_am_pm = datetime.now().strftime("%p") // 4 pm

current_microseconds = datetime.now().strftime("%f") // 623596 Rarely we need.

current_timzone = datetime.now().strftime("%Z") // UTC, EST, CST etc. (empty string if the object is naive).

Reference: 8.1.7. strftime() and strptime() Behavior

Reference: strftime() and strptime() Behavior

The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.

e.g.
my_date = "23-02-2018 00:00:00"

datetime.strptime(str(my_date),"%d-%m-%Y %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S+00:00")

datetime.strptime(str(my_date),"%d-%m-%Y %H:%M:%S").strftime("%m")

And so on...

Answer #4

class Switch:
    def __init__(self, value):
        self.value = value

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        return False # Allows a traceback to occur

    def __call__(self, *values):
        return self.value in values


from datetime import datetime

with Switch(datetime.today().weekday()) as case:
    if case(0):
        # Basic usage of switch
        print("I hate mondays so much.")
        # Note there is no break needed here
    elif case(1,2):
        # This switch also supports multiple conditions (in one line)
        print("When is the weekend going to be here?")
    elif case(3,4):
        print("The weekend is near.")
    else:
        # Default would occur here
        print("Let"s go have fun!") # Didn"t use case for example purposes

Answer #5

calendar.monthrange provides this information:

calendar.monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2)  # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren"t leap years
(0, 28)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Answer #6

Use weekday():

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

From the documentation:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

Answer #7

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.

In Python 3.9+ isocalendar() returns a namedtuple with the fields year, week and weekday which means you can access the week explicitly using a named attribute:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar().week
24

Answer #8

Use calendar.monthrange:

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

As @mikhail-pyrev mentions in a comment:

First number is weekday of first day of the month, second number is number of days in said month.

Answer #9

Pandas is great for time series in general, and has direct support for date ranges.

For example pd.date_range():

import pandas as pd
from datetime import datetime

datelist = pd.date_range(datetime.today(), periods=100).tolist()

It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range.

See date range documentation

In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.

EDIT by OP:

If you need actual python datetimes, as opposed to Pandas timestamps:

import pandas as pd
from datetime import datetime

pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()

#OR

pd.date_range(start="2018-09-09",end="2020-02-02")

This uses the "end" parameter to match the original question, but if you want descending dates:

pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()

Answer #10

A week number is not enough to generate a date; you need a day of the week as well. Add a default:

import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + "-1", "%Y-W%W-%w")
print(r)

The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:

2013-07-01 00:00:00

%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.

See the strftime() and strptime() behaviour section in the documentation, footnote 4:

When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.

Note, if your week number is a ISO week date, you"ll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.

Tutorials