Integer difference in python between two dates - python

I've RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn't....
I just want an integer. Not a "timedelta object." Not an "aware yet hashable object" (see, I RTFM). Not a tuple. Not a dictionary. Just a simple freaking integer so I can use an if statement and branch and be happy. Please bring the light of your wisdom upon this, with thanks.
Here's what I have
...
import datetime
mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.strptime(rdate, "%Y-%m-%d")
delta = datetime.timedelta.days(mdate1 - rdate1)
Here's what I get:
pmain.py:4: AttributeError: 'module' object has no attribute 'strptime'
(error hits in the 'mdate1..." line above)
And, that doesn't mean that my delta line is going to work -- please look at that one, too.

You want to get the classmethod datetime.datetime.strptime(), then take the .days attribute from the resulting timedelta:
import datetime
mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
delta = (mdate1 - rdate1).days
So you have the datetime module, which has a datetime.datetime class, which in turn has a datetime.datetime.strptime() method on it. I also added calls to .date() to extract just the date portion (result is a datetime.date instance); this makes dealing with timestamps that differ slightly less than a multiple of 24 hours easier.
Demo:
>>> import datetime
>>> mdate = "2010-10-05"
>>> rdate = "2010-10-05"
>>> mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
>>> rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
>>> delta = (mdate1 - rdate1).days
>>> print delta
0
>>> type(delta)
<type 'int'>

sign1['days'] = sign1['diff'] / np.timedelta64(1, 'D')
I had the same problem and it solved by uding the above statement.
I hope it helps.

import datetime
mdate = "2010-11-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d")
delta = (mdate1 - rdate1).days

Related

Python how to save datetime.strptime in datetime.time format

So I was trying to make a simple code using datetime and came across an error.
import time
from datetime import datetime
x = True
b = datetime.strptime("06:10", "%H:%M")
while x == True:
a = datetime.now().time()
print(a)
if a > b:
x = False
time.sleep(0.945)
As a result I get
TypeError: unorderable types: datetime.time() > datetime.datetime()
So I was wondering if it's possible to save a datetime.strptime in the datetime.time() format.
Thanks in advance
You tried to compare a datetime and time object, which Python won't let you compare.
If you do datetime.strptime() you get an object which holds a date and time (called datetime). But because you do not also parse the date it defaults to 01-01-1900. Now datetime.now() also gets you a datetime object but with the current date. So directly comparing datetime.now() and b won't work because the dates are different.
Now you already use the current time only by doing datetime.now().time(), so you also need to apply that to b by doing b = b.time() somewhere before the comparison.
use 'datetime.now()' insted of 'datetime.now().time()'
Compare .time() of both a and b as:
if a > b.time(): # if you want to compare only time
and not the datetime objects. Reason at the end of the answer.
datetime.now().time() is of datetime.time type:
>>> type(datetime.now().time())
<type 'datetime.time'>
whereas, datetime.strptime() and datetime.now() are of datetime.datetime type:
>>> type(datetime.strptime("06:10", "%H:%M"))
<type 'datetime.datetime'>
>>> type(datetime.now())
<type 'datetime.datetime'>
Edit based on comment from Martijn.
On creating datetime object like datetime.strptime("06:10", "%H:%M") date will be set as 1900-01-01. And definitely I dont't think you want to compare with that. You may check the date as:
>>> d = datetime.strptime("06:10", "%H:%M")
>>> d
datetime.datetime(1900, 1, 1, 6, 10)

How to subtract datetimes / timestamps in python

Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:
2015-08-10 19:33:27.653
2015-08-10 19:31:28.209
How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.
Parse your strings as datetime.datetime objects and subtract them:
from datetime import datetime
d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")
print(d1 - d2)
Gives me:
0:01:59.444000
Also check out timedelta documentation for all possible operations.
you can do subtraction on 2 datetime objects to get the difference
>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10
convert your strings to datetime objects with time.strptime
datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
timedelta.seconds does not represent the total number of seconds in the timedelta, but the total number of seconds modulus 60.
Call the function timedelta.total_seconds() instead of accessing the timedelta.seconds property.
For python 3.4, first you'd need to convert the strings representing times into datetime objects, then the datetime module has helpful tools work with dates and times.
from datetime import datetime
def to_datetime_object(date_string, date_format):
s = datetime.strptime(date_string, date_format)
return s
time_1 = '2015-08-10 19:33:27'
time_2 = '2015-08-10 19:31:28'
date_format = "%Y-%m-%d %H:%M:%S"
time_1_datetime_object = to_datetime_object(time_1, date_format)
time_2_datetime_object = to_datetime_object(time_2, date_format)
diff_time = time_1_datetime_object - time_2_datetime_object

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

how to get the date from datetime

I have a datetime object and I'm trying to individually get a string with the date, and one with the time. I'd like the values for theDate and theTime to be strings.
theDate = myDatetime.date()
theTime = myDatetime.time()
Something along those lines. I tried str(datetime.date) but it gave me a reference in memory, any other ideas? Thanks in advance for any help.
Use the datetime.strftime() method on the datetime object:
theDate = myDatetime.strftime('%Y-%m-%d')
theTime = myDatetime.strftime('%H:%M:%S')
Alternatively, turn your date and time objects into strings for their default string representations:
theDate = str(myDatetime.date())
theTime = str(myDatetime.time())
Demo:
>>> import datetime
>>> myDatetime = datetime.datetime.now()
>>> myDatetime.strftime('%Y-%m-%d')
'2013-06-19'
>>> myDatetime.strftime('%H:%M:%S')
'16:49:44'
>>> str(myDatetime.date())
'2013-06-19'
>>> str(myDatetime.time())
'16:49:44.447010'
The default string format for datetime.time objects includes the microsecond component.

Creating DateTime from user inputted date

I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.
I've got the model of:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
and then create an instance with:
memory = Memory()
memory.author = users.get_current_user()
memory.content = self.request.get('content')
But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21
I've tried:
memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d')
memory.date = db.DateProperty(self.request.get('date'))
memory.date = self.request.get('date') (wishful thinking I guess)
and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:
: No
module named _multiprocessing
args = ('No module named _multiprocessing',)
message = 'No module named _multiprocessing'
I have no idea what to make of that.
I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not.
What am I missing on something that would seem to be so simple.
perhaps you are using the wrong class? I'm not sure what type your model should take
but try:
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d')
I use a datetime object in MySQL with MySQLdb (and a datetime field)
...likewise you can try
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
(notice the [obj].date() at the end)
Yeah, PHP's is much nicer. I'm using this library
http://labix.org/python-dateutil
>>> import dateutil.parser
>>> dateutil.parser.parse("may 2 1984")
datetime.datetime(1984, 5, 2, 0, 0)
You were right with strptime:
>>> dt = time.strptime('2009-07-21', '%Y-%m-%d')
>>> dt
time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec
=0, tm_wday=1, tm_yday=202, tm_isdst=-1)
>>>
You got struct that can be used by other functions. For example display date in M/D/Y convention:
>>> time.strftime('%m/%d/%Y', dt)
'07/21/2009'
Another example (import datetime module):
>>> dt = datetime.datetime.strptime('2009-07-21', '%Y-%m-%d')
>>> td = datetime.timedelta(days=20)
>>> dt+td
datetime.datetime(2009, 8, 10, 0, 0)

Categories