I have a code like this:
import time
from datetime import date
startyear = raw_input("start year: ")
startmonth = raw_input("start month: ")
startday = raw_input("start day: ")
endyear = raw_input("end year: ")
endmonth = raw_input("end month: ")
endday = raw_input("end day: ")
startdate = date(int(startyear), int(startmonth), int(startday))
while startdate < date(int(endyear), int(endmonth), int(endday)):
print startdate
startdate = startdate.replace(day=startdate.day + 1)
what this code does is:
1.get start and end date by manual input
2.generate a list of dates between them
but the problem is, if I set up the date like, for example,
startdate: 2012-10-28
enddate: 2012-11-4
the output would be like:
2012-10-28
2012-10-29
2012-10-30
2012-10-31
ValueError: day is out of range for month
I want the output to be like:
2012-10-28
2012-10-29
2012-10-30
2012-10-31
2012-11-01
2012-11-02
2012-11-03
2012-11-04
So I want the dates to go through month.
any suggestions? any help would be really great.
Instead of startdate.replace(), you should use timedelta...
from datetime import date, timedelta
# Get input here...
while startdate < date(int(endyear), int(endmonth), int(endday)):
print startdate
startdate += timedelta(days=1)
There's a module called python-dateutil which is very useful for this kind of thing:
from datetime import datetime
from dateutil.rrule import rrule, DAILY
list(rrule(DAILY, dtstart=datetime(2012, 11, 24), until=datetime(2012,11,30)))
# [datetime.datetime(2012, 11, 24, 0, 0), datetime.datetime(2012, 11, 25, 0, 0), datetime.datetime(2012, 11, 26, 0, 0), datetime.datetime(2012, 11, 27, 0, 0), datetime.datetime(2012, 11, 28, 0, 0), datetime.datetime(2012, 11, 29, 0, 0), datetime.datetime(2012, 11, 30, 0, 0)]
And has other options, for instance, by days of the week (useful to only include MO, TU, WE, TH, FR for working weeks):
from dateutil.rrule import MO, WE
list(rrule(DAILY, byweekday=[MO, WE], dtstart=datetime(2012, 11, 24), until=datetime(2012,11,30))
# [datetime.datetime(2012, 11, 26, 0, 0), datetime.datetime(2012, 11, 28, 0, 0)]
Related
I have this code and I want to count the days between 2 dates.
from datetime import date, datetime
checkin= datetime(2022, 1, 30, 1, 15, 00)
checkout= datetime(2022, 1, 31, 0, 0, 00)
count_days= (checkout - checkin).days
In this case, the result of count_days result is 0, because in an operation with 2 datetimes, it takes into account hours, minutes and seconds.
I want the result to be 1 because is +1 day of difference. Type of variables must be datetimes. Thanks!
Convert them to dates first, with the date method.
from datetime import date, datetime
checkin = datetime(2022, 1, 30, 1, 15, 00)
checkout = datetime(2022, 1, 31, 0, 0, 00)
count_days = (checkout.date() - checkin.date()).days
Could you do something like this?
(assuming you want a minimum since the solution you have is similar)
from datetime import date, datetime
check_in= datetime(2022, 1, 30, 1, 15, 00)
check_out= datetime(2022, 1, 31, 0, 0, 00)
# Number of days between two dates (min 1 day)
days = (check_out - check_in).days + 1
print(days)
I would like to filter pandas using the time stamp. This works fine for all hours except 0. If I filter for dt.hour = 0, only the date is displayed and not the time. How can I have the time displayed too?
import datetime
df = pd.DataFrame({'datetime': [datetime.datetime(2005, 7, 14, 12, 30),
datetime.datetime(2005, 7, 14, 0, 0),
datetime.datetime(2005, 7, 14, 10, 30),
datetime.datetime(2005, 7, 14, 15, 30)]})
print(df[df['datetime'].dt.hour == 10])
print(df[df['datetime'].dt.hour == 0]
use strftime:
print(df[df['datetime'].dt.hour == 0].datetime.dt.strftime("%Y-%m-%d %H:%M:%S"))
The result is:
1 2005-07-14 00:00:00
Name: datetime, dtype: object
I want to get all the dates between two dates excluding weekends dates.
Below is the format of dates:
last_date = '2019-01-21'
curr_date = '2019-02-04'
Using date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday
is 6.
from datetime import timedelta, date
def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 + timedelta(n)
start_dt = date(2019,1,21)
end_dt = date(2019,2,4)
weekdays = [5,6]
for dt in daterange(start_dt, end_dt):
if dt.weekday() not in weekdays: # to print only the weekdates
print(dt.strftime("%Y-%m-%d"))
EDIT:
Using date.isoweekday():
Return the day of the week as an integer, where Monday is 1 and Sunday
is 7.
weekdays = [6,7]
for dt in daterange(start_dt, end_dt):
if dt.isoweekday() not in weekdays:
print(dt.strftime("%Y-%m-%d"))
OUTPUT:
2019-01-21
2019-01-22
2019-01-23
2019-01-24
2019-01-25
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-04
You can do this quite nicely with the dateutil library's rrule.
Example:
from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR
last_date = '2019-01-21'
curr_date = '2019-02-04'
result = rrule(
DAILY,
byweekday=(MO,TU,WE,TH,FR),
dtstart=parse(last_date),
until=parse(curr_date)
)
print(list(result))
Result:
[datetime.datetime(2019, 1, 21, 0, 0),
datetime.datetime(2019, 1, 22, 0, 0),
datetime.datetime(2019, 1, 23, 0, 0),
datetime.datetime(2019, 1, 24, 0, 0),
datetime.datetime(2019, 1, 25, 0, 0),
datetime.datetime(2019, 1, 28, 0, 0),
datetime.datetime(2019, 1, 29, 0, 0),
datetime.datetime(2019, 1, 30, 0, 0),
datetime.datetime(2019, 1, 31, 0, 0),
datetime.datetime(2019, 2, 1, 0, 0),
datetime.datetime(2019, 2, 4, 0, 0)]
How do I get the time from a string and the date from today?
datetime.datetime.strptime("7:30PM", "%I:%M%p")
Gives me a datetime.datetime(1900, 1, 1, 19, 30), but I'd like it to have today's date and year.
One of the possible option is combine:
t = datetime.datetime.strptime("7:30PM", "%I:%M%p").time()
datetime.datetime.combine(datetime.datetime.today().date(), t)
output:
datetime.datetime(2016, 12, 27, 19, 30)
I want to write a function that returns a tuple of (start,end) where start is the Monday at 00:00:00:000000 and end is Sunday at 23:59:59:999999. start and end are datetime objects. No other information is given about day, month or year. i tried this function
def week_start_end(date):
start= date.strptime("00:00:00.000000", "%H:%M:%S.%f")
end = date.strptime("23:59:59.999999", "%H:%M:%S.%f")
return (start,end)
print week_start_end(datetime(2013, 8, 15, 12, 0, 0))
should return (datetime(2013, 8, 11, 0, 0, 0, 0), datetime(2013, 8, 17, 23, 59, 59, 999999))
but the function returns tuple with dates (datetime.datetime(1900, 1, 1, 0, 0), datetime.datetime(1900, 1, 1, 23, 59, 59, 999999))
I think using datetime.isocalendar is a nice solution. This give the correct outputs for your example:
import datetime
def iso_year_start(iso_year):
"The gregorian calendar date of the first day of the given ISO year"
fourth_jan = datetime.date(iso_year, 1, 4)
delta = datetime.timedelta(fourth_jan.isoweekday()-1)
return fourth_jan - delta
def iso_to_gregorian(iso_year, iso_week, iso_day):
"Gregorian calendar date for the given ISO year, week and day"
year_start = iso_year_start(iso_year)
return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)
def week_start_end(date):
year = date.isocalendar()[0]
week = date.isocalendar()[1]
d1 = iso_to_gregorian(year, week, 0)
d2 = iso_to_gregorian(year, week, 6)
d3 = datetime.datetime(d1.year, d1.month, d1.day, 0,0,0,0)
d4 = datetime.datetime(d2.year, d2.month, d2.day, 23,59,59,999999)
return (d3,d4)
As an example:
>>> d = datetime.datetime(2013, 8, 15, 12, 0, 0)
>>> print week_start_end(d)
(datetime.datetime(2013, 8, 11, 0, 0), datetime.datetime(2013, 8, 17, 23, 59, 59, 999999))
And should help you with your problem.