Created
November 12, 2011 08:03
-
-
Save kisom/1360224 to your computer and use it in GitHub Desktop.
Test for the weekend using C-style time constructs in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
def is_weekend(date, date_is_timestamp=False, format='%Y-%m-%d'): | |
""" | |
Check to see if a date falls on a weekend. | |
You can pass in date as a string. By default, is_weekend expects to see | |
a date in the format YYYY-mm-dd (ex. 2011-11-10). You can change this | |
using the strftime(3) format specifiers and passing the format in the | |
'format' argument. | |
You can also use a UNIX timestamp. If so, format is ignored and you | |
should set the 'date_is_timestamp' argument to True. | |
This demonstrates using the C time functions strptime, mktime, etc... | |
to determine whether it's the weekend. An easier method might be the | |
calender module. | |
""" | |
if date_is_timestamp: | |
fmt = '%c' | |
day = time.strptime(time.asctime(time.localtime(date)), '%c') | |
else: | |
day = time.strptime(date, format) | |
day = time.strftime('%a', day) | |
if 'Sat' == day or 'Sun' == day: | |
return True | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment