subtract one day from timestamp - python - python

'I'm trying to subtract a day from this date 1590074712 in order to make 1590008151 but can't figure out any way to achieve that.
I've tried with:
from datetime import datetime
ts= 1590074712
date = datetime.timestamp(ts) - timedelta(days = 1)
print(date)
How can I subtract a day from a date in the above format?
I want the output in timestamp

Use datetime.fromtimestamp():
from datetime import datetime, timedelta
ts= 1590074712
date = datetime.fromtimestamp(ts) - timedelta(days = 1)
print(date)
Prints:
2020-05-20 15:25:12

Related

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.

Wrong output on adding 2 days in current date or today date using python

I am adding 2 days in current date or today date using python but getting wrong output, please at look at code below i used ::
from datetime import date
from datetime import timedelta
time_diff =str(timedelta(days=2))
d =str(date.today().strftime("%Y-%m-%d") ) + time_diff
print(d.split("day")[0])
OUTPUT ::2020-04-262
i think it should show the output ::2020-04-28.
You don't need all those str() calls. You want to add the time delta to a time, you don't want to add two strings together (that just concatenates).
Just add the time delta to the date:
from datetime import timedelta
time_diff = timedelta(days=2)
a_date = date.today() + time_diff
a_date_string = a_date.strftime("%Y-%m-%d")
print(a_date_string)
# 2020-04-28

Set start date to beginning of the year and end date to one day prior to current date

I am trying to set startdate and enddate in python but ran across some problem. What i want is start date set to beginning of the year and enddate set to one day prior to current date.
from datetime import datetime, timedelta, time,date
my_str= '2020-01-01'
stdate= datetime.strptime(my_str,'%Y-%m-%d')
print(stdate)
edate = datetime.now() - timedelta(days = 1)
print(edate)
Right now the output is date with time.But i only want to output date not time
2020-01-01 00:00:00
2020-03-01 12:25:50.542813
from datetime import date, timedelta
start_of_current_year = date(date.today().year, 1, 1)
end_of_previous_year = start_of_current_year - timedelta(days=1)
# Check values
print(start_of_current_year)
print(end_of_previous_year)

How to get a specific date from the previous month given the current date in python?

I want to get the 20th of previous month, given the current_date()
I am trying to use time.strftime but not able to subtract the value from it.
timestr = time.strftime("%Y-(%m-1)%d")
This is giving me error. The expected output is 2019-03-20 if my current_date is in April. Not sure how to go about it.
I read the posts from SO and most of them address getting the first day / last day of the month. Any help would be appreciated.
from datetime import date, timedelta
today = date.today()
last_day_prev_month = today - timedelta(days=today.day)
twenty_prev_month = last_day_prev_month.replace(day=20)
print(twenty_prev_month) # 2019-03-20
Use datetime.replace
import datetime
current_date = datetime.date.today()
new_date = current_date.replace(
month = current_date.month - 1,
day = 20
)
print(new_date)
#2019-03-20
Edit
That won't work for Jan so this is a workaround:
import datetime
current_date = datetime.date(2019, 2, 17)
month = current_date.month - 1
year = current_date.year
if not month:
month, year = 12, year - 1
new_date = datetime.date(year=year, month=month, day=20)
I imagine it is the way dates are parsed. It is my understanding that with your code it is looking for
2019-(03-1)20 or 2019-(12-1)15, etc..
Because the %y is not a variable, but a message about how the date is to be expected within a string of text, and other characters are what should be expected, but not processed (like "-")
This seems entirely not what you are going for. I would just parse the date like normal and then reformat it to be a month earlier:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
print("{}-{}-{}".format(year, int(month)-1, day))
This would be easier with timedelta objects, but sadly there isn't one for months, because they are of various lengths.
To be more robust if a new year is involved:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
if month in [1, "01", "1"]: # I don't remember how January is represented
print("{}-{}-{}".format(int(year) - 1, 12, day)) # use December of last year
else:
print("{}-{}-{}".format(year, int(month)-1, day))
This will help:
from datetime import date, timedelta
dt = date.today() - timedelta(30)// timedelta(days No.)
print('Current Date :',date.today())
print(dt)
It is not possible to do math inside a string passed to time.strftime, but you can do something similar to what you're asking very easily using the time module
in Python 3
# Last month
t = time.gmtime()
print(f"{t.tm_year}-{t.tm_mon-1}-20")
or in Python 2
print("{0}-{1}-{2}".format(t.tm_year, t.tm_mon -1, 20))
If you have fewer constraints, you can just use the datetime module instead.
You could use datetime, dateutil or arrow to find the 20th day of the previous month. See examples below.
Using datetime:
from datetime import date
d = date.today()
month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)
last_month = d.replace(day=20, month=month, year=year)
print(last_month)
Using datetime and timedelta:
from datetime import date
from datetime import timedelta
d = date.today()
last_month = (d - timedelta(days=d.day)).replace(day=20)
print(last_month)
Using datetime and dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta # pip install python-dateutil
d = date.today()
last_month = d.replace(day=20) - relativedelta(months=1)
print(last_month)
Using arrow:
import arrow # pip install arrow
d = arrow.now()
last_month = d.shift(months=-1).replace(day=20).datetime.date()
print(last_month)

Python Get Date In Future (x) Days, And Hours Left To Date?

How can I get date + time in the future from now by days? in this format: 10/08/2013 9:50 PM (dd/mm/yyyy) and also I would like Time left to date in hours for this new future date?
You need to use a datetime in combination with a timedelta object.
Like this:
from datetime import datetime, timedelta
dt = datetime.now()
td = timedelta(days=4)
# your calculated date
my_date = dt + td

Categories