How to Split a substract of a date in python - python

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!

Related

I have a list of dates and I want to subtract actual date from each of them to know how many day passed. Is there any fast way to do this?

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.

Find No.of days between two dates (Tuples)

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)

Python: Convertion of seconds from an initial date to datetime

I have measurements taken from 1st January 1993. They were recorded in second elapsed from that date. I would like to have them in date time.
I know in MatLab the function would be
time = datenum(1993,01,01,00,00, time)
However, I struggle to find an equivalent function in Python.
I have tried:
datetime.fromordinal(time) doesn't work because 'module object has no attribute fromordinal'?
datetime.datetime(time) doesn't work (I have a matrix because there are many scans done)
https://docs.python.org/3/library/datetime.html
You will first have to create a datetime object for Jan 1st 1993 and then add the number of seconds to that date. The code below should help you get started.
from datetime import datetime, timedelta
original_date = datetime.strptime('01-01-1993', '%d-%m-%Y')
original_date + timedelta(seconds= 10000)
output: datetime.datetime(1993, 1, 1, 2, 46, 40)
Let us say you have list of timevalues in seconds starting from 1993-01-01 00:00.
Easiest would be:
datevec=[datetime.datetime(1993,1,1,0)+datetime.timedelta(seconds=val) for val in timevector]
It is like UNIX time, but with a different start.
You can compute the offset once:
>>> import datetime as dt
>>> dt.datetime(1993,1,1).timestamp()
725842800.0
and use it in your program:
OFFSET = 725842800.0
mydate = dt.datetime.fromtimestamp(OFFSET + seconds_from_1993)

Python - Time delta from string and now()

I have spent some time trying to figure out how to get a time delta between time values. The only issue is that one of the times was stored in a file. So I have one string which is in essence str(datetime.datetime.now()) and datetime.datetime.now().
Specifically, I am having issues getting a delta because one of the objects is a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this including the following:
Python - Date & Time Comparison using timestamps, timedelta
Comparing a time delta in python
Convert string into datetime.time object
Converting string into datetime
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following:
2014-01-05 13:09:42.348000
time.strptime returns a struct_time.
datetime.datetime.now() returns a datetime object.
The two can not be subtracted directly.
Instead of time.strptime you could use datetime.datetime.strptime, which returns a datetime object. Then you could subtract now and then.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
By the way, you need to supply a date format string to time.strptime or DT.datetime.strptime.
time.strptime(date)
should have raised a ValueError.
It looks like your date string is 26 characters long. That might mean you have a date string like 'Fri, 10 Jun 2011 11:04:17 '.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like %Y, %m, etc.) here.
Try this:
import time
import datetime
d = datetime.datetime.now()
now = time.mktime(d.timetuple())
And then apply the delta
if you have the year,month,day of 'then' you may use:
year = 2013
month = 1
day = 1
now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)
delta = now_date - then_date

how to create a date object in python representing a set number of days

I would like to define a variable to be a datetime object representing the number of days that is entered by the user. For example.
numDays = #input from user
deltaDatetime = #this is what I'm trying to figure out how to do
str(datetime.datetime.now() + deltaDatetime)
This code would print out a datetime representing 3 days from today if the user entered 3 as their input. Any idea how to do this? I'm completely lost as to an effective approach to this problem.
EDIT: Because of how my system is set up, the variable storing the "deltaDatetime" value must be a datetime value. As I said in the comments, something like 3 days becomes Year 0, January 3rd.
It's fairly straightforward using timedelta from the standard datetime library:
import datetime
numDays = 5 # heh, removed the 'var' in front of this (braincramp)
print datetime.datetime.now() + datetime.timedelta(days=numDays)
deltaDateTime = datetime.timedelta(days=3)
Use timedelta:
from datetime import datetime, timedelta
days = int(raw_input())
print datetime.now() + timedelta(days=days)

Categories

Resources