Python DateTime minus TimeDelta vs TimeDelta minus DateTime - python

Say I have the datetime now:
import datetime
now = datetime.datetime(2019, 10, 3, 1, 57, 3, 939862)
print(now)
2019-10-03 01:57:03.939862
and I have a timedelta for the start of business day (07:00:00).
start_biz_dt = datetime.timedelta(hours = 7)
I want to do a calculation that gives me the time from now to start of business day.
ie, I want:
6:03:56.060138
But I obviously cannot do:
start_biz_dt - now
I could give start_biz_dt the same date as now, but I have many datetimes in a column of various dates, so this might not be the best way. Any help is appreciated.

To find closest 07:00:00, so you can use next code:
from datetime import datetime, timedelta
start_of_business_day = datetime.now().replace(hour=7, minute=0, second=0)
if start_of_business_day < datetime.now():
start_of_business_day += timedelta(days=1)
To calculate how much left just substitute current datetime from start_of_business_day:
sleep_time = start_of_business_day - datetime.now()

Related

Given number of days and date then find the start or end date in python

I understand there's an package "date" from "datetime"
for solving "Calculate numbers of days between two given date", but this is not what I am looking for
Let me give an example to further describe my question.
let says:10 days and the baseline is 2021/09/09
I want to know the date before 10 days 8/30 is clearly the answer I am looking for
It might be an easy question. still needs for help. Thanks
This might just work:
from datetime import date, timedelta
day1 = date(2021, 9, 9)
difference = timedelta(days=10)
day2 = day1 - difference #Your answer
print(day2)
try this
from datetime import datetime
from datetime import timedelta
print(datetime.now() - timedelta(days=10))
i think you are looking for this. You can also pass day as datetime object
from datetime import datetime, timedelta
def get_start_end_day(day, delta):
if isinstance(day, str):
day = datetime.strptime(day, '%Y/%m/%d')
return day - timedelta(days=delta), day + timedelta(days=delta)
days = get_start_end_day('2021/09/09', 10)
print(days)
output
(datetime.datetime(2021, 8, 30, 0, 0), datetime.datetime(2021, 9, 19, 0, 0))

find start and end date of previous month from current date in python

I need to find the start and end date of the previous month from the current date.
If the current date is 03-Feb-2021
The start date should be 01-Jan-2021 and the end date should be 31-Jan-2021.
how to achieve this as each month have a different number of days? Do we have any function in datetime to achieve this?
>>> from datetime import date, timedelta
>>> this_first = date.today().replace(day=1)
>>> prev_last = this_first - timedelta(days=1)
>>> prev_first = prev_last.replace(day=1)
>>> prev_first, prev_last
(datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))
Format if/as needed.
first date will always be the 1st
# month_date = (datetime.now() - timedelta(days=20))
month_date = datetime.now().replace(day= monthrange(month_date.year,month_date.month - 1)[1]).strftime("%Y/%m/%d")
start_date = month_date.strftime("%Y/%m/01")
end_date = month_date.replace(day= monthrange(month_date.year,month_date.month)[1]).strftime("%Y/%m/%d")
imports are
from datetime import datetime, timedelta
from calendar import monthrange
you can add one condition for january so it will take december. If have any problem with that just add comment I will add that too.

python: adding any number of days to date

I am hoping someone can point me in the right direction in working with dates and timedelta.
my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta.
if that is correct, how can I add any number to a date when it is an integer?
any documentation or links would be great - thank you.
code example, my date is as follows:
x = 20100103 (formatted as YYYYMMDD)
>>> import datetime
>>> today = datetime.datetime.now().date()
>>> today
datetime.date(2016, 6, 14)
>>> today + datetime.timedelta(days=10)
datetime.date(2016, 6, 24)
There's no need to convert it to a timedelta. Just use the timedelta function, if you want to add days, use days=N, for hours, timedelta(hours=20)
x=20100103
x2 = int((datetime.datetime.strptime(str(x),"%Y%m%d") + datetime.timedelta(days=10)).strftime("%Y%m%d"))
to break it down
x=20100103
x_as_datetime = datetime.datetime.strptime(str(x),"%Y%m%d")
new_datetime = x_as_datetime + datetime.timedelta(days=10) #add your timedelta
x2 = new_datetime.strftime("%Y%m%d") # format it back how you want
int(x2) # if you just want an integer ...
from datetime import datetime
from datetime import timedelta
StartDate = "20100103"
Date = datetime.strptime(StartDate, "%Y%m%d")
EndDate = Date + timedelta(days=10)

Expand date to the beginning and end datetime for the day

Based on the current time (datetime.now()) I want to expand this to cover the whole days time.
Right now I have been using:
start = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
end = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Problem is that this is 24 hours from the current date. If it is 12pm noon that means it should only look back 12 hours as I want to search for the current days records.
How can I accomplish this in Python?
I hope this makes sense, I just gave very descriptive variable names
from datetime import datetime
from datetime import timedelta
now = datetime.now()
start_of_day = datetime(now.year,now.month,now.day)
delta_since_start_of_day = now - start_of_day
delta_till_end_of_day = timedelta(days=1) - delta_since_start_of_day
end_of_day = start_of_day + timedelta(days=1)
Here's another solution that directly resets the time - no math required. Uses datetime.replace():
now = datetime.now()
day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
day_end = day_start + timedelta(hours=24)
It seems you could accomplish what you wish like so:
from datetime import datetime, time
now = datetime.now()
start = datetime.combine(now, time.min) # datetime.datetime(2021, 11, 5, 0, 0)
end = datetime.combine(now, time.max) # datetime.datetime(2021, 11, 5, 23, 59, 59, 999999)
No need for maths, replacing, timedeltas.
I just use datetime.time.max in this way:
now = datetime.now()
day_end = datetime.datetime.combine(now, datetime.time.max)

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Categories