Python Datetime doing not working properly [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Is there a function to determine which quarter of the year a date is in?
(18 answers)
Closed 1 year ago.
I am trying to def a function which will return the current quarter of the year in a string.
import datetime
date = datetime.datetime(2022,1,1)
month = date.month
year = date.year
if month ==1 or 2 or 3:
quarter = 'Q1'
if month ==4 or 5 or 6:
quarter = 'Q2'
if month ==7 or 8 or 9:
quarter = 'Q3'
if month ==10 or 11 or 12:
quarter = 'Q4'
lookup = quarter +str(year)
print(lookup)
when I run this function I get Q42022. Am I missing something in the if/or statements.
Any help would be greatly appreciated.

You have to explicitly specify
if month==1 or month==2 or month==3:
You could also check inclusion
if month in (1, 2, 3):

if month in {1, 2, 3}:
# and so on

Related

Python multiple possibilities in if statement

I am new to python and I have an assignment to print month names with corresponding numbers.
How can I make an if statement with multiple conditions so I don't need to make twelve of them?
Normally it would be :
if month == 1
print(one) # one = January
Can I make it something like :
if month == [1,2,3,4,5,6]
print [one,two.three, etc.]
I tried it and it does not work, but I am wondering if it is possible?
You'd better save that in a dict, to get mappings month index -> month name
months = {1: "January", 2: "February"}
month = 1
if month in months:
print(months[month])
Or with calendar
import calendar
month = 1
if month in range(13):
print(calendar.month_name[month])
Use Dictionary
months = {1:"Jan", 2:"Feb", 3:"March" ... and so on}
if inputMonth in months:
print(months[inputMonth])
or you can use List
months = ["Jan", "Feb", "March"... ]
inputMonth = 1
if inputMonth in range(0,13):
print(months[inputMonth-1])

How to check if today is Monday in Python [duplicate]

This question already has answers here:
Find Monday's date with Python
(8 answers)
How do I get the day of week given a date?
(30 answers)
Closed 5 years ago.
How would I write a statement that says:
If today is Monday, then run this function.
My thoughts are:
if datetime.now().day == Monday:
run_report()
But I know this is not the right way to do it. How would I properly do this?
You can use date.weekday() like this:
from datetime import date
# If today is Monday (aka 0 of 6), then run the report
if date.today().weekday() == 0:
run_report()
import datetime as dt
dt.date.today().isoweekday() == 1 # 1 = Monday, 2 = Tues, etc.
Both datetime.date and datetime.datetime
objects have a today method that return respectively a Date and a Datetime object.
Which both have a weekday and isoweekday methods.
weekday count from Monday = 0, while isoweekday count from Monday = 1:
from datetime import date, datetime
if date.today().weekday() == 0:
# it is Monday
if datetime.today().isoweekday() == 1:
# it is Monday
See documentation

Round Date in Pandas Dataframe [duplicate]

This question already has an answer here:
Pandas: convert date in month to the 1st day of next month
(1 answer)
Closed 5 years ago.
I'm attempting to round the date from this dataframe below to the 1st day of the next month - i.e. 1997-10-10 would result in 1997-11-01:
Date
1997-10-10
1997-05-27
1997-04-30
1997-12-19
1997-08-12
Currently my code looks like:
df = pd.read_csv(XXX)
df['Date'] = pd.to_datetime(df.Date)
df['Date'] = df['Date'].dt.date.replace(day = 1)
According to the python library documentation,
date.replace(year=self.year, month=self.month, day=self.day)
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, if d == date(2002, 12, 31), then d.replace(day=26) == date(2002, 12, 26).
I had presumed that I could use .replace with only 1 argument - day -however I'm receiving a number of errors.
I think you need MonthBegin(0):
df['Date'] = pd.to_datetime(df.Date) + pd.offsets.MonthBegin(0)
print (df)
Date
0 1997-11-01
1 1997-06-01
2 1997-05-01
3 1998-01-01
4 1997-09-01

how to get week number on python? [duplicate]

This question already has answers here:
Python: Number of the Week in a Month
(9 answers)
Closed 7 years ago.
I want to get week number like picture below
If I insert 20150502, It should print "week 1".
If I insert 20150504, It should print "week 2".
If I insert 20150522, It should print "week 4".
How to get week number?
Here's a quick attempt, as with all date/time code there are probably a lot of edge cases that can cause strange results.
# dateutil's parser is very good for converting from string to date
from dateutil.parser import parse
date_strs = ['20150502', '20150504', '20150522']
for date_str in date_strs:
d = parse(date_str)
month_start = datetime.datetime(d.year, d.month, 1)
week = d.isocalendar()[1] - month_start.isocalendar()[1] + 1
print(date_str + ':', week)
Output:
20150502: 1
20150504: 2
20150522: 4

How do we determine the number of days for a given month in python [duplicate]

This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 9 years ago.
I need to calculate the number of days for a given month in python. If a user inputs Feb 2011 the program should be able to tell me that Feb 2011 has 28 days. Could anyone tell me which library I should use to determine the length of a given month?
You should 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 the weekday of the first day of the month, the second number is the number of days in said month.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Categories