I am trying to count the number of Friday the 13ths per year from 1950-2050 using Python (I know, a little late). I am not familiar with any date/calendar packages to use. Any thoughts?
This has a direct solution. Use sum to count the number of times where the 13th of the month is a Friday:
>>> from datetime import datetime # the function datetime from module datetime
>>> sum(datetime(year, month, 13).weekday() == 4
for year in range(1950, 2051) for month in range(1,13))
174
the datetime.date class has a weekday() function that gives you the day of the week (indexed from 0) as an integer, so Friday is 4. There's also isoweekday() that indexes days from 1, it's up to you which you prefer.
Anyway, a simple solution would be:
friday13 = 0
months = range(1,13)
for year in xrange(1950, 2051):
for month in months:
if date(year, month, 13).weekday() == 4:
friday13 += 1
Is it some kind of exercise or homework? I faintly remember of having solved it. I can give you a hint, I seem to have used Calendar.itermonthdays2 Of course there should be other ways to solve it as well.
Sounds like homework. Hint (weekday 4 is a Friday):
import datetime
print(datetime.datetime(1950,1,13).weekday())
While other solutions are clear and simple, the following one is more "calendarist". You will need the dateutil package, which is installable as a package:
from datetime import datetime
from dateutil import rrule
fr13s = list(rrule.rrule(rrule.DAILY,
dtstart=datetime(1950,1,13),
until=datetime(2050,12,13),
bymonthday=[13],
byweekday=[rrule.FR]))
# this returns a list of 174 datetime objects
You see these five arguments of rrule.rrule: Take every rrule.DAILY (day) between dtstart and until where bymonthday is 13 and byweekday is rrule.FR (Friday).
from datetime import *
from time import strptime
yil = input("yilni kiritnig:: ")
kun1 = "01/01/"+yil
kun1 = datetime.strptime(kun1, "%d/%m/%Y")
while 1:
if kun1.strftime("%A") == "Friday":
break
kun1 = kun1 + timedelta(days=1)
count = 0
while 1:
if int(kun1.strftime("%Y")) == int(yil)+1:
break
if kun1.strftime("%d") == "13":
count+=1
kun1=kun1+timedelta(days=7)
print(count)
Related
Determine a date (as day, month, year) starting from two integer numbers that represent the year and the number of the day in that year.
i'm new to coding and I don't know where to start even.
If I understand correctly you can use Python datetime module to do what you need:
from datetime import datetime
print(datetime.strptime("2004-68", "%Y-%j").strftime("%d.%m.%Y"))
Result:
08.03.2004
You can start with creating algorithm in your head, or on paper.
Then you can translate it to python code.
or
you can read documentation about datetime lib in python and try to combine functions to you desired output. https://docs.python.org/3/library/datetime.html
For example:
from datetime import datetime, timedelta
year = 2004
days = 68
date = datetime(year, 1, 1) + timedelta(days=days-1)
# days-1 is needed because we already start with first day in year
print(date)
# 2004-03-08 00:00:00
year=int(input("year="))
days=int(input("number of days="))
day=int
month = days/28 + 1
m = int(month)
if ((year % 400 == 0) or
(year % 100 != 0) and
(year % 4 == 0)) :
day = days % 30
else:
day = days % 30 + 1
print(day,".", m, ".",year)
is this any good? or more preciseley is it corect? like i need this more basic aproach to the problem
How can I extract last three month names in Python? If I am running this today then I would like to see May, June and July as my result.
Easier way is to use "%B" using datetime and timedelta
from dateutil.relativedelta import relativedelta
from datetime import datetime
today = datetime.now()
for i in range(1,4):
print((today - relativedelta(months=i)).strftime('%B'))
Output:
July
June
May
One way is to use the python calendar module, and list slice a month name for a given, extracted datetime month.
.month_name returns a list of all the month names.
calendar is part of the standard library.
For timedelta, there isn't a month parameter because the length of a month is not a constant value, so use days, as an approximation.
See datetime for the available methods.
datetime is part of the python standard library, so doesn't require a separate installation.
Use .month to extract the month from the datetime.
from datetime import datetime, timedelta
import calendar
# get the time now
now = datetime.now()
# iterate through 3 different timedeltas as an example
for x in range(1, 4):
new = now - timedelta(days=31*x)
print(calendar.month_name[new.month])
[out]:
July
June
May
As mentioned in the answer by bigbounty, using .strftime with '%B' is a better option than using calendar
However, unlike the dateutil module, timedelta still doesn't have a month parameter.
The dateutil module provides powerful extensions to the standard datetime module and must be installed, and then imported.
# get the time now
now = datetime.now()
# iterate through 3 different timedeltas as an example
for x in range(1, 4):
new = now - timedelta(days=31*x)
print(new.strftime('%B'))
[out]:
July
June
May
Best way to do this is a combination of the date and calendar modules.
date.today().month will give you a numerical value for the current month (1-12)
calendar.month_name[x] will give you the name for the month represented by the number x
the % operator will be used to wrap around the index of the month_name object to avoid the pesky 0 index returning ''
Putting them together we have:
from datetime import date
from calendar import month_name
def previous_n_months(n):
current_month_idx = date.today().month - 1 # Value is now (0-11)
for i in range(1, n+1):
# The mod operator will wrap the negative index back to the positive one
previous_month_idx = (current_month_idx - i) % 12 #(0-11 scale)
m = int(previous_month_idx + 1)
print(month_name[m])
Example usage:
>>> previous_n_months(3)
July
June
May
I have two integers, one represents the year and one is the number of the day in that year.
Example: 2004 and 68
I have to find a way to turn the 68 into 8.03.2004
I just started using Python and I don't really know how to use the datetime command. If anyone could give me some tips it would be nice ;)
You can use datetime.timedelta to advance from the beggining of year:
from datetime import datetime, timedelta
# we start from day 1, not day 0, so we need to substract one day
print(datetime(2004, 1, 1) + timedelta(days=68 - 1))
# 2004-03-08 00:00:00
One way to calculate it:
import datetime
year = 2004
day_of_year = 68
print datetime.date(year,1,1) + datetime.timedelta(days=day_of_year-1)
I would like to define a variable to be a datetime object representing the number of days that is entered by the user. For example.
numDays = #input from user
deltaDatetime = #this is what I'm trying to figure out how to do
str(datetime.datetime.now() + deltaDatetime)
This code would print out a datetime representing 3 days from today if the user entered 3 as their input. Any idea how to do this? I'm completely lost as to an effective approach to this problem.
EDIT: Because of how my system is set up, the variable storing the "deltaDatetime" value must be a datetime value. As I said in the comments, something like 3 days becomes Year 0, January 3rd.
It's fairly straightforward using timedelta from the standard datetime library:
import datetime
numDays = 5 # heh, removed the 'var' in front of this (braincramp)
print datetime.datetime.now() + datetime.timedelta(days=numDays)
deltaDateTime = datetime.timedelta(days=3)
Use timedelta:
from datetime import datetime, timedelta
days = int(raw_input())
print datetime.now() + timedelta(days=days)
Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
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.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.