I would like to know how many days are passed from a x ago to today
I wrote this:
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")
now = datetime.now()
today = now.strftime("%d")
print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)
But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(
Exact format with date time hour minute accuracy
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
print(f"daysBefore {daysBefore} - today {today}")
The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.
Therefore the recommend method is as #abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.
Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)
Related
How to add hours to a timestamp in python?
I have a timestamp in UTC, and I want to add hours to it. If I convert it to DateTime, it changes to local time. So, I want to add hours directly to the timestamp without converting to datetime.
import time
from datetime import datetime, timedelta
input = datetime(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
today = datetime.now()
days = (today - input).days
d = datetime(year=today.year, month=today.month, day=today.day) - timedelta(seconds=time.timezone) - timedelta(days=days)
utc_midnight_timestamp = int(time.mktime(d.utctimetuple()))
Now I want to keep adding 1 hour to the utc_midnight_timestamp many times
for x in range(1,24):
#Need to keep incrementing utc_midnight_timestamp by x hours
#use timestamp later
Given two dates, I would like to generate a list of dates with a fixed time length in between one another using datetime, starting from the later date.
For instance, given 01/01/2018 and 01/09/2018 and time interval of 2 months the output would be:
[01/01/2018, 01/03/2018, 01/05/2018, 01/07/2018, 01/09/2018]
For an interval of 3 months:
[01/03/2018, 01/06/2018, 01/09/2018]
I cannot just subtract months using the .replace method on a datetime object since going from a 31 days month to a 30 days month would return an error.
I think relativedeleta module can help you on this - pip install python-dateutil
from dateutil.relativedelta import *
import datetime
date1 = datetime.datetime.strptime('01/01/2018', "%d/%m/%Y").date()
date2 = datetime.datetime.strptime('01/09/2018', "%d/%m/%Y").date()
f = [(date1 + relativedelta(months=i)).strftime("%d/%m/%Y") for i in range(date1.month, date2.month,2)]
Result will be - ['01/02/2018', '01/04/2018', '01/06/2018', '01/08/2018']
You did specify datetime, but if you're interested,
a time.localtime object can be broken down like so:
import time
secSinceEpoch = time.time()
currentTime = time.localtime(secSinceEpoch)
month = currentTime.tm_mon
day = currentTime.tm_mday
year = currentTime.tm_year
hour = currentTime.tm_hour
min = currentTime.tm_min
sec = currentTime.tm_sec
From here you could perform operations on specific parts of the date/time...
I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.
from datetime import date
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
dataStart=start.split(".")
days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])
endYears=0
endMonths=0
endDays=0
dateStart = date(years, months, days)
while end>=365:
end-=365
endYears+=1
else:
while end>=30:
end-=30
endMonths+=1
else:
while end>=1:
end-=1
endDays+=1
dateEnd = date(endYears, endMonths, endDays)
For adding days into date, you need to user datetime.timedelta
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))
You may use datetime.timedelta to add certain units of time to your datetime object.
See the answers here for code snippets: Adding 5 days to a date in Python
Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:
>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)
It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.
Below is a small snippet on how to use it:
import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date() # to get the date format of the endDate
If you have any doubts please look at the documentation python3/python2.
If 17:00:00 today is already passed, then it should be today's date, otherwise - yesterday's.
Today's time I get with:
test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)
But I don't want to have future time. How can I fix it?
You could check if the current time is less than 17:00, if so, substract one day from the generated time object:
test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)
if datetime.datetime.now() < test:
test = test - datetime.timedelta(days=1)
Better use the datetime.time of today directly for comparing the times. Then use datetime.timedelta to do the math:
if datetime.datetime.now().time() > datetime.time(17,0):
# today, as it's after 17 o'clock
test = datetime.date.today()
else:
# yesterday, as it's before 17 o'clock
test = datetime.date.today() - datetime.timedelta(days=1)
set test as today or yesterday depending on the time of day:
from datetime import datetime, date, timedelta
if datetime.now().strftime('%H:%M') > '17:00':
test = date.today()
else:
test = date.today() - timedelta(days=1)
Pythons datetime functions are indeed quite unhandy sometimes. While you can use datetime.timedelta objects for your case, to substract times in days, e.g. upcounting month or years becomes annoying. So in case you sooner or later not only want to add one day, maybe give this function a try:
import datetime
import calendar
def upcount(dt, years=0, months=0, **kwargs):
"""
Python provides no consistent function to add time intervals
with years, months, days, minutes and seconds. Usage example:
upcount(dt, years=1, months=2, days=3, hours=4)
"""
if months:
total_months = dt.month + months
month_years, months = divmod(total_months, 12)
if months == 0:
month_years -= 1
months = 12
years += month_years
else:
months = dt.month
years = dt.year + years
try:
dt = dt.replace(year=years, month=months)
except ValueError:
# 31st march -> 31st april gives this error
max_day = calendar.monthrange(years, months)[1]
dt = dt.replace(year=years, month=months, day=max_day)
if kwargs:
dt += datetime.timedelta(**kwargs)
return dt
I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days
Thanks for any help.
minus_seven = today - datetime.timedelta(days = 7)
The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:
Between 1 and the number of days in the given month of the given year.
You can see why this works later in the month; but for the first few days of the month you end up with a negative value.
The docs immediately go on to document the correct way to do what you're trying to do:
date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.