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)
Related
How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04
I'm trying to get current date so I can pass it to the DATE field in SQL. I'm using datetime.datetime, below is my code:
from datetime import datetime
dt = datetime.strptime(datetime.today().date(), "%m/%d/%Y").date()
However, i'm getting this error:
TypeError: strptime() argument 1 must be str, not datetime.datetime
How can I fix the issue above? I'm still confused about datetime and datetime.datetime, and i want to keep using from datetime import datetime not import datetime.
How can I fix the issue above? thank you
If you see closely, the result of following statement,
>>> datetime.today().date()
datetime.date(2019, 9, 30)
>>> str(datetime.today().date())
'2019-09-30'
You'll notice that the datetime returned is - seperated and you'll have to convert it explicitly to a string value. Hence, for the above statement to work, change it to :
dt = datetime.strptime(str(datetime.today().date()), "%Y-%M-%d").date()
Then change it to whatever format you desire for using strftime (in your case >>> "%d/%m/%Y")
>>> dt.strftime("%d/%m/%Y")
'30/01/2019'
Just use datetime.strftime:
from datetime import datetime
dt = datetime.today().strftime("%m/%d/%Y")
print(dt)
Prints:
'09/30/2019'
strptime takes a string and makes a datetime object. Whereas strftime does exactly the opposite, taking a datetime object and returning a string.
Is there any way to automatically parse strings with time only to datetime.time object (or something similar)? Same for datetime.date.
I've tried dateutil, arrow, moment, pandas.to_datetime.
All these parsers create timestamps with a current date.
>>> from dateutil.parser import parse
>>> parse('23:53')
datetime.datetime(2019, 1, 8, 23, 53) # datetime.time(23, 53) expected
>>> parse('2018-01-04')
datetime.datetime(2018, 1, 4, 0, 0) # datetime.date(2018, 1, 4) expected
UPD:
Thanks for the responses. Think that I should clarify the problem.
The program doesn't know what will be in the input (timestamp, date or time), and it should decide to set appropriate type. The problem is to distinguish these types.
For example, I can parse 23:53 and get a timestamp. How can I decide to extract the time from it or not?
You can use fromisoformat() from datetime.
import datetime
datetime.time.fromisoformat('23:53')
datetime.date.fromisoformat('2018-01-04')
What you basically want is for '23:53' to become a datetime.time object and for '2018-01-04' to become a datetime.date object. This cannot be achieved by using dateutil.parser.parse():
Returns a datetime.datetime object or, if the fuzzy_with_tokens option is True, returns a tuple, the first element being a datetime.datetime object, the second a tuple containing the fuzzy tokens.
From the documentation. So you'll always get a datetime.datetime object when using dateutil.parser.parse()
I would guess you need to interpret the input string yourself to define wether you're trying to parse a time or a date. When you do that, you can still use the dateutil.parser.parse() function to get the object you want:
from dateutil.parser import parse
my_time = parse('23:53')
my_time.time() # datetime.time(23, 53)
my_time.date() # datetime.date(2019, 1, 8)
Here you have an example. Just set the date attributes with replace, and select the output with strftime.
import datetime
date = datetime.datetime.now()
newdate = date.replace(hour=11, minute=59)
print(newdate.strftime('%H:%M'))
newdate2 = date.replace(year=2014, month=1, day=3)
print(newdate2.strftime('%Y-%m-%d'))
You can use either time or datetime modules, but one thing to bear in mind, is that these always create an object, that specifies a moment in time. (Also, if parsing strings, consider using the strptime function and displaying as string, strftime function respectively)
e.g.
>>> hours = time.strptime("23:59", "%H:%M")
>>> days = time.strptime("2018-01-04", "%Y-%m-%d")
>>> time.strftime("%H:%M", hours)
'23:59'
>>> time.strftime("%H:%M %Y", hours)
'23:59 1900'
Not recommended, but if you wish to separate these two object for some reason and wish to only care for a specific portion of your assignement, you can still adress the respective numbers with
>>> hours.tm_hour
23
>>> hours.tm_min
59
>>> days.tm_mon
1
>>> days.tm_mday
4
>>> days.tm_year
2018
A far better approach, in my opinion would be formatting the complete date string and using the strptime to form a complete timestamp - even if you get the time and date as separate inputs:
>>> ttime = "22:45"
>>> dday = "2018-01-04"
You can use the % formatter, or the "new" python f-Strings
>>> complete_t_string = "{} {}".format(dday, ttime)
>>> complete_t_string
'2018-01-04 22:45'
Now that we have a complete string, we can specify how it should be read and create a complete timestamp:
>>> complete_time = time.strptime(complete_t_string, "%Y-%m-%d %H:%M")
>>> complete_time
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=4, tm_hour=22, tm_min=45, tm_sec=0, tm_wday=3, tm_yday=4, tm_isdst=-1)
EDIT:
Somebody will probably kill me, but if you absolutely know that you will only get two types of values, you could just do a simple try / except construct. It can probably be written more Pythonically:
try:
time.strptime(t_string, "%H:%M")
except ValueError:
time.strptime(t_string, "%Y-%m-%d")
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
Here's a little snippet that I'm trying execute:
>>> from datetime import *
>>> item_date = datetime.strptime('7/16/10', "%m/%d/%y")
>>> from_date = date.today()-timedelta(days=3)
>>> print type(item_date)
<type 'datetime.datetime'>
>>> print type(from_date)
<type 'datetime.date'>
>>> if item_date > from_date:
... print 'item is newer'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.date
I can't seem to compare the date and the datetime values. What would be the best way to compare these? Should I convert the datetime to date or vice-versa? How do i convert between them.
(A small question but it seems to be a little confusing.)
Use the .date() method to convert a datetime to a date:
if item_date.date() > from_date:
Alternatively, you could use datetime.today() instead of date.today(). You could use
from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)
to eliminate the time part afterwards.
I am trying to compare date which are in string format like '20110930'
benchMark = datetime.datetime.strptime('20110701', "%Y%m%d")
actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")
if actualDate.date() < benchMark.date():
print True
Here is another take which preserves information in case both the inputs are datetimes and not dates, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:
datetime.datetime(d.year, d.month, d.day)
Suggestion:
from datetime import datetime
def ensure_datetime(d):
"""
Takes a date or a datetime as input, outputs a datetime
"""
if isinstance(d, datetime):
return d
return datetime.datetime(d.year, d.month, d.day)
def datetime_cmp(d1, d2):
"""
Compares two timestamps. Tolerates dates.
"""
return cmp(ensure_datetime(d1), ensure_datetime(d2))
In my case, I get two objects in and I don't know if it's date or timedate objects. Converting to date won't be good as I'd be dropping information - two timedate objects with the same date should be sorted correctly. I'm OK with the dates being sorted before the datetime with same date.
I think I will use strftime before comparing:
>>> foo=datetime.date(2015,1,10)
>>> bar=datetime.datetime(2015,2,11,15,00)
>>> foo.strftime('%F%H%M%S') > bar.strftime('%F%H%M%S')
False
>>> foo.strftime('%F%H%M%S') < bar.strftime('%F%H%M%S')
True
Not elegant, but should work out. I think it would be better if Python wouldn't raise the error, I see no reasons why a datetime shouldn't be comparable with a date. This behaviour is consistent in python2 and python3.
Create and similar object for comparison works too
ex:
from datetime import datetime, date
now = datetime.now()
today = date.today()
# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
print(True)
two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
print("this will work with datetime too")
I got you bro
you can use timetuple function to compare between date obj and datetime obj
>>> from datetime import datetime
>>> date_obj=datetime.utcnow().date()
>>> type(date_obj)
<type 'datetime.date'>
>>> datetime_obj=datetime.utcnow()
>>> type(datetime_obj)
<type 'datetime.datetime'>
>>> datetime_obj.timetuple()
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=2, tm_min=12, tm_sec=43, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> date_obj.timetuple()
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> type(datetime_obj.timetuple())
<type 'time.struct_time'>
>>> type(date_obj.timetuple())
<type 'time.struct_time'>
>>> date_obj.timetuple()<datetime_obj.timetuple()
True