I have this function where it calculates today. I am wondering why is the following results are happening.
today = datetime.datetime.now()
shows as 2018-06-13 17:13:42.372469
today = datetime.datetime.now().date()
shows as 2018-06-13
but when I try to use timedelta like this:
today = datetime.datetime.now().date() + datetime.timedelta(hours=-8)
it shows 2018-06-12. A full day back instead of 8 hours (should show 2018-06-13 9:13:42)
Can someone please explain why this happens and have timedelta correctly go back 8 hours instead of a day?
By reducing the timestamp to the date only, you have effectively set the time to 00:00:00 - substracting 8 hours from 2018-06-13 midnight correctly results in 2018-06-12.
Why not use the correct timestamps for calculation, and only convert them to dates after you have performed them?
Related
I need to calculate the date based on the number of minutes from the start of the year. I just need the day and month.
I have tried a few different classes within Python datetime but I can not get the desired result.
for example, at 1700 today, minutes since the 01/01/2022 is 263100
print(datetime.timedelta(0,0,0,0,263100))
This returns
182 days, 17:00:00
Before I explicitly write out the months and how many days they have and work it out that way, is there something already built in that I am missing within datetime?
I think this is what you are looking for. We add the minutes timedelta to the start datetime, and return it formatted.
from datetime import datetime, timedelta
def datesince_min(min:int, start:tuple=(2022,1,1)) -> str:
date = datetime(*start) + timedelta(minutes=min)
return date.strftime("%A, %B %d, %Y %I:%M:%S")
print(datesince_min(263100)) #Saturday, July 02, 2022 06:00:00
For more information regarding strftime formatting, refer to this.
Before I explicitly write out the months and how many days they have and work it out that way...
You shouldn't ever have to do that, and if you did it would almost certainly have to be for a system or language that is in development.
I found this code that should do the trick:
number_of_days = ((datetime.timedelta(0,0,0,0,263100)).split())[0]
months = (number_of_days - years * 365) // 30
days = (number_of_days - years * 365 - months*30)
print(months, days)
Where you replace 263100 with whatever minutes you wish ofc
(source: https://www.codesansar.com/python-programming-examples/convert-number-days-years-months-days.htm#:~:text=Python%20Source%20Code%3A%20Days%20to%20Years%2C%20Months%20%26,print%28%22Months%20%3D%20%22%2C%20months%29%20print%28%22Days%20%3D%20%22%2C%20days%29)
:)
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
I am working on a time lapse program and I would like to be able to pause overnight over multiple days. I am using military time and when I try say 18:00:00 as pause start and 08:00:00 as pause end I get a negative number. I could probably take the difference between 24:00:00 and 18:00:00 and 0:00:00 and 08:00:00 and add them to get the answer, but I'm wondering if there is something I'm missing in the datetime module that would allow me to do this?
from datetime import datetime
pause_start=input('Enter pause start time as 24 hrs (hh:mm:ss): ')
pause_end=input('Enter pause end time as 24 hrs (hh:mm:ss): ')
pause_start=datetime.strptime(pause_start, '%H:%M:%S')
pause_end=datetime.strptime(pause_end, '%H:%M:%S')
total_pause_time=(pause_end-pause_start).total_seconds()
print(total_pause_time)
input:18:00:00
input:08:00:00
output:-36000.0
I tried an input of 25:00:00 and received an error saying time data did not match format '%H:%M:%S' therefore I believe it is being read correctly as military time.
What you are missing, is that you are calculating with times on the same day. So you are subtracting the later time from the earlier time which gives a negative result. I see two solutions:
Add 24 hours to the final result to get the correct offset.
Create datetime objects so that 18:00:00 is today and 08:00:00 is tomorrow morning. Then subtract the dates.
Hi everyone I have a code like this to calculate the exact day on six_months back but unfortunately it prints the yy-mm-dd format and I want the dd/mm/yy format how do I do it(I tried to convert but it doesn't work)?What's wrong with my code?
import datetime
six_months = str(datetime.date.today() - datetime.timedelta(6*365/12-1)
datetime.datetime.strptime(six_months, '%Y-%m-%d').strftime('%d/%m/%y')
expected output=04/02/2017
current output=2017-02-04
The code is fine, you just forgot to save to result of
datetime.datetime.strptime(six_months, '%Y-%m-%d').strftime('%d/%m/%y')
to any variable. strptime doesn't change the object it is called on in any way, it returns a string.
I reckon your algorithm for computing 6 months back doesn't correspond to the real-world understanding of that phrase. Six months back from 4 August is 4 February and your computation gives the right answer for that. But six months back from 4 September is 4 March, and your computation gives the answer 7 March.
Your code also unnecessarily formats the computed date to a string, and then has to parse the string back into a date to get the dd/mm/yy format you want.
import datetime
from dateutil.relativedelta import *
six_months = datetime.date.today() + relativedelta(months=-6)
print (f"{six_months:%d/%m/%y}")
Output (until tomorrow) is
04/02/17
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.