I am given a number like: 737556.5965277777.
>>> datetime.timedelta(days=737556.5965277777)
datetime.timedelta(days=737556, seconds=51539, microseconds=999996)
>>> datetime.datetime.now()
datetime.datetime(2020, 5, 11, 15, 36, 41, 711686)
How can I compare this with the current datetime to check whether it is after? Either get the current timedelta and compare those or convert it to a timestamp first, then compare.
One way would be to convert the current datetime to an ordinal, and then compare the two. If the ordinal datetime is greater than the now() ordinal datetime, then it is after.
You can use datetimes toordinal()
from datetime import datetime as dt
dt_now = dt.now()
ordinal_date = dt_now.toordinal()
print(ordinal_date)
The ordinal datetime is just a number of day starting with date 0001-01-01 (as day 1). So you can just add the timedelta (minus one day, to compensate for 0001-01-01 not being day 0) to that date:
yourdate = datetime.datetime(1,1,1) + datetime.timedelta(days=737556.5965277777 - 1)
and compare it to now:
if yourdate > datetime.datetime.now():
Note that yourdate.toordinal() returns the integer part of your initial number: 737556.
Related
I am trying to compare the current date in the following format (ddmmyyyy) to a future date in the following format (ddmmyyyy)
I put them in that format so i can easily compare them as integers. However, it keeps failing the if then test.
from datetime import datetime, timedelta
StartDay=datetime.today() # Get current date in this format 2020-04-28 19:59:16.901897
EndDay=StartDay+timedelta(60) # I want to be able to add 60 days to StartDay
print(EndDay.strftime('%d%m%Y')) # Print EndDay as an integer 27062020
EndDay=EndDay.strftime('%d%m%Y') # Convert EndDay to make it look like an integer
StartDay=datetime.today().strftime('%d%m%Y') # Convert the StartDay to make it look like an integer
if int(StartDay)>int(EndDay):
print('Game Over!')
else:
pass
What I want to achieve is the an integer value for a date, such that the future date will always be greater than past/current date if that makes sense.
you can directly compare datetime objects, no need for a detour here:
from datetime import datetime
t0, t1 = datetime(2020,1,1), datetime(2020,1,2)
t0>t1
Out[6]: False
t0<t1
Out[7]: True
t1-t0
Out[8]: datetime.timedelta(days=1)
datetime.datetime might be easily converted into datetime.date and then compared consider following example:
from datetime import datetime, timedelta
StartDay = datetime.today()
EndDay = StartDay + timedelta(60)
StartDate = StartDay.date() # datetime.date(2020, 4, 28)
EndDate = EndDay.date() # datetime.date(2020, 6, 27)
print(StartDate < EndDate) # True
Note that you might also compare datetime.datetime directly with datetime.datetime but this take in account also units smaller than days, so if you have two datetime.datetimes say d1 and d2 with same year-month-day but different hours, then result of d1 < d2 might be different from d1.date() < d2.date()
Keep startdate and enddate as 'datetime' and do the following:
from datetime import datetime, timedelta
StartDay=datetime.today()
EndDay=StartDay+timedelta(60)
delta = (StartDay - EndDay).days
if delta > 0:
print('Game Over!')
else:
print('Something else')
This should do the trick
Given a string that looks like "Hours:5 Minutes:34 Seconds:28" or "Minutes:34 Seconds:28", is there any pythonic way to convert it to a datetime object? I do not want to use a regex if there's an easier way.
Yes, there is. You can do it like this:
import time
datetime_string = "Hours:5 Minutes:34 Seconds:28"
if "Hours" in datetime_string:
datetime_object = time.strptime(datetime_string, "Hours:%H Minutes:%M Seconds:%S")
elif "Minutes" in datetime_string:
datetime_object = time.strptime(datetime_string, "Minutes:%M Seconds:%S")
else:
datetime_object = time.strptime(datetime_string, "Seconds:%S")
Note: When You create datetime object, values that You do not provide will be filled with default values.So, in case datetime_string contains only seconds, hours and minutes will be set to 0.
You may use datetime.strptime() to convert string into datetime object as:
>>> from datetime import datetime
>>> date_object = datetime.strptime('Hours:5 Minutes:34 Seconds:28', 'Hours:%H Minutes:%M Seconds:%S')
>>> date_object
datetime.datetime(1900, 1, 1, 5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
Since you do not have date in the string, it will keep the default date of 1 Jan 1990. I think what you need is datetime.time() which return time object with same hour, minute, second and microsecond as in you datetime object. (tzinfo is None). For example:
>>> date_object.time()
datetime.time(5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
where date_object is of datetime type created earlier.
I need to compare dates in this format:
'03/31/2018' # month/day/year
I tried to use the datetime module:
from datetime import datetime as dt
dt.strptime("03/31/2018", "%m/%d/%y")
But I got this error:
ValueError: unconverted data remains: 18
If I use a two digit year:
dt.strptime("03/31/18", "%m/%d/%y")
It works, but in this case I need to compare using the whole four digits year
You need to use a big Y
>>> from datetime import datetime as dt
>>> dt.strptime("03/31/2018", "%m/%d/%Y")
datetime.datetime(2018, 3, 31, 0, 0)
I need to construct datetime object from different parameters. For example, I get these parameters:
integer number from 0 to 6. This one indicates weekday.
hour and minutes in float format (from 0.0 to 24.0).
And then I know which week of the current year it is going to be. So, for example, let say that datetime should be from 2014-07-18 00:00:00 to 2014-07-24 23:59:00 (seconds can be ignored and left at 00). So to get exact datetime I need to use above defined parameters.
Let say I would get these parameters 4 (meaning Friday), and 9.5 (meaning 09:30).
So by doing such construction, I should get a date that would be: 2014-07-22 09:30:00. How could accomplish such thing?
Do I need to somehow get for example day of the month by knowing which is the week of the year and which weekday it is?
P.S. A bit more detailed example of what I'm trying to accomplish
from datetime import datetime
today = datetime.today() #using this to get the week I'll be working with.
today = today.replace(day=?) #how to get which day I
#need to enter by having weekday and knowing that week is the present one?
You could do something like that, if your parameters are weekday and t (time):
from datetime import timedelta
monday = today - timedelta(days=today.weekday())
result = (monday + timedelta(days=weekday)).replace(hour=int(t), minutes=int((t - int(t)) * 60))
If you have a starting date, use the relative value of the datetime.datetime.weekday() value to construct a timedelta() object that'll put you onto the right weekday, then replace the hour and minutes:
from datetime import timedelta
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday() - weekday
return (reference - timedelta(days=days)).replace(
hour=int(hour), minute=int(minute), second=0, microsecond=0)
Demo:
>>> from datetime import timedelta, datetime
>>> def relative_date(reference, weekday, timevalue):
... hour, minute = divmod(timevalue, 1)
... minute *= 60
... days = reference.weekday() - weekday
... return (reference - timedelta(days=days)).replace(
... hour=int(hour), minute=int(minute), second=0, microsecond=0)
...
>>> relative_date(datetime.now(), 4, 9.5)
datetime.datetime(2014, 8, 22, 9, 30)
>>> relative_date(datetime.now() - timedelta(days=30), 6, 11.75)
datetime.datetime(2014, 7, 27, 11, 45)
I would use timedelta to add the difference between weekdays to the datetime
from datetime import datetime, timedelta
friday = 4
today = datetime.now()
friday_this_week = today + timedelta(friday - today.weekday())
In your case just replace today with a date that is in the week you want.
A function returns date and time in unicode format.
u'2014-03-06T04:38:51Z'
I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.
Thanks in advance
Check string is unicode
>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True
Converting strings to datetime:
>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)
Subtract from today to
>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)
First you have to convert your string to a datetime.datetime object.
import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")
then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.
now = datetime.datetime.now()
Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.
for delta in (now-then, then-now):
print(delta, "::", delta.days, delta.seconds, delta.microseconds)
This prints out:
-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858
Best try it with a few examples to convince yourself it's correct.