Suppose I have a tuple A. It contains two nested tuples. The nested tuples are dates of the form DD,MM,YYYY.
A = ((DD,MM,YYYY), (DD,MM,YYYY))
Now, I want to find the number of days between the two dates. I've already tried fiddling with datetime module and it only helps when objects are integers and not tuples. My problem constraint is that I cannot change the structure in which dates are represented. I suppose I can use slicing but that would be way too much work. I'm pretty new at this and I hope someone can shed some light my way.
You can use datetime.strptime to create a datetime object from the given string. Then you can subtract date1 and date2 which gives you a timedelta object and this timedelta object has a nice attribute days which gives you the number of days between two dates.
Use:
from datetime import datetime
date1 = datetime.strptime("-".join(A[0]), "%d-%m-%Y")
date2 = datetime.strptime("-".join(A[1]), "%d-%m-%Y")
diff_days = (date1 - date2).days
print(diff_days)
For example consider,
A = (("24","05","2020"), ("25","04","2020")) then the above code will print diff_days as 29.
why is slicing too much work?
import datetime
# A = ((DD,MM,YYYY), (DD,MM,YYYY))
A = ((1,1,2020), (20,4,2020))
delta = (
datetime.date(A[1][2],A[1][1],A[1][0])-
datetime.date(A[0][2],A[0][1],A[0][0])
)
Code written on my smartphone. Basic idea convert with datetime and a f string to datetime object within a list comprehension. Build the timedelta and finally get the result in different formats
A=((3,4,2000), (4,4,2000))
from datetime import datetime
dt = [datetime.strptime(f'{a[0]}.{a[1]}.{a[2]}','%d.%m.%Y') for a in A]
td = dt[1] - dt[0]
# when you want a tuple w only days
difference_tuple = (td.days)
# days, hours, minutes
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
difference_tuple2 = (days, hours, minutes)
Related
I know I should import datetime to have actual date. But the rest is black magic for me right now.
ex.
dates = ['2019-010-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = datetime.datetime.now()
How can I subtract this and as a result have new list with days that passed by from dates to actual_date?
If I'm understanding correctly, you need to find the current date, and then find the number of days between the current date and the dates in your list?
If so, you could try this:
from datetime import datetime, date
dates = ['2019-10-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = date.today()
days = []
for date in dates:
date_object = datetime.strptime(date, '%Y-%m-%d').date()
days_difference = (actual_date - date_object).days
days.append(days_difference)
print(days)
What I am doing here is:
Converting the individual date strings to a "date" object
Subtracting the this date from the actual date. This gets you the time as well, so to strip that out we add .days.
Save the outcome to a list, although of course you could do whatever you wanted with the output.
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 want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22
I am just wondering how best to approach using this 24 hour time format as a predictive feature. My thoughts were to bin it into 24 categories for each hour of the day. Is there an easy way to convert this object into a python datetime object that would make binning easier or how would you advise handling this feature? Thanks :)
df['Duration']
0 2:50
1 7:25
2 19:00
3 5:25
4 4:45
5 2:25
df['Duration'].dtype
dtype('O')
The best solution will depend on what you hope to get from your model. In many cases it makes sense to convert it to total number of seconds (or minutes or hours) since some epoch. To convert your data to seconds since 00:00, you can use:
from datetime import datetime
t_str = "2:50"
t_delta = datetime.strptime(t_str, "%H:%M") - datetime(1900, 1, 1)
seconds = t_delta.total_seconds()
hours = seconds/60**2
print(seconds)
# 10200.0
Using Python's datetime class will not support time values over 23:59. Since it appears that your data may actually be a duration, you may want to represent it as an instance of Python's timedelta class.
from datetime import timedelta
h, m = map(int, t_str.split(sep=':'))
t_delta = timedelta(hours=h, minutes=m)
# Get total number of seconds
seconds = t_delta.total_seconds()
You can use datetime to create a useable datetime string
>>> from datetime import datetime
>>> x = datetime(2019, 1, 1, 0).strftime('%Y-%m-%d %H:%M:%S')
>>> # Use that for your timestring then you can reverse it nicely back into a datetime object
>>> d = datetime.strptime('2019-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
Of course you can use any valid format string.
You should calculate the time in seconds or minutes or hours from some initial time like the 1st time. Then you can make an x-y scatter plot of the data since the x-axis (time) is now numbers.
I wish to get the total duration of a relativedelta in terms of days.
Expected:
dateutil.timedelta(1 month, 24 days) -> dateutil.timedelta(55 days)
What I tried:
dateutil.timedelta(1 month, 24 days).days -> 24 (WRONG)
Is there a simple way to do this? Thanks!
This one bothered me as well. There isn't a very clean way to get the span of time in a particular unit. This is partly because of the date-range dependency on units.
relativedelta() takes an argument for months. But when you think about how long a month is, the answer is "it depends". With that said, it's technically impossible to convert a relativedelta() directly to days, without knowing which days the delta lands on.
Here is what I ended up doing.
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
rd = relativedelta(years=3, months=7, days=19)
# I use 'now', but you may want to adjust your start and end range to a specific set of dates.
now = datetime.now()
# calculate the date difference from the relativedelta span
then = now - rd
# unlike normal timedelta 'then' is returned as a datetime
# subtracting two dates will give you a timedelta which contains the value you're looking for
diff = now - then
print diff.days
Simple date diff does it actually.
>>> from datetime import datetime
>>> (datetime(2017, 12, 1) - datetime(2018, 1, 1)).days
-31
To get positive number You can swap dates or use abs:
>>> abs((datetime(2017, 12, 1) - datetime(2018, 1, 1)).days)
31
In many situations you have a much restricted relativedelta, in my case, my relativedelta had only relative fields set (years, months, weeks, and days) and no other field. You may be able to get away with the simple method.
This is definitely off by few days, but it may be all you need
(365 * duration.years) + (30 * duration.months) + (duration.days)