Can I easily get datetime with less resolution in Python? - python

Obviously I can get the date and time from datetime.datetime.now(), but I don't actually care about the seconds or especially microseconds.
Is there somewhere I can easily get Date+Hour+Minute?

You can clear down the second and microsecond component of a datetime value like so:
dt = datetime.datetime.now()
#Now get rid of seconds and microseconds component:
dt = dt.replace(second=0, microsecond=0)
This would allow you to compare datetimes to minute granularity.
If you just want to print the date without a second/microsecond component, then use the appropriate format string:
dt = datetime.datetime.now()
print dt.strftime("%Y/%m/%d %H:%M")
>>> '2012/12/12 12:12'

Related

How to Split a substract of a date in 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!

Datetime formatting

The api I am working with gives time is the following format when I place an order.
'orderDateTime': '12-May-2020 14:54:11'
What I am looking to do is to find the number of minutes/seconds that have passed since I placed the order. So if it has already been for example 10 minutes, if I would like to cancel or modify the order I can do it.
I have tried everything I know to convert the given time format to do what I want but have been unsuccessful. Please help. Thanks in advance.
time_now = datetime.now()
print("Time now is",time_now)
t1 = time_now.strftime("%d-%b-%Y %H:%M:%S")
print(t1)
trade_time = datetime(12-May-2020 15:01:32)
t2 = datetime.strftime(trade_time,"%d-%b-%Y %H:%M:%S")
print(t2)
You are mixing the datetime objects and their representation as strings.
What you need to do is convert your trade time to a datetime object, by using the strptime method. strftime does the opposite, it produces a formatted text representation of your datetime.
Then, you can subtract the two datetime objects, which will give you the difference as a timedelta, from which you can get the difference as a number of seconds.
So, your code should look like:
from datetime import datetime
time_now = datetime.now()
trade_time_as_str = '12-May-2020 15:01:32'
trade_time = datetime.strptime(trade_time_as_str,"%d-%b-%Y %H:%M:%S")
elapsed = time_now - trade_time
elapsed_seconds = elapsed.total_seconds()
print(elapsed_seconds)
# 15808.77104

How to combine dates and times?

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

Python - Calculate last quarter hour of current time

How do I round the time to last quarter hour for the current time. I am able to find the last quarter hour minute, however, not able to fit this into the correct time format.
import datetime
import time
time = datetime.datetime.now()
last_quarter_minute = 15*(time.minute//15)
current_time = time.strftime("%Y/%m/%d %H:%M")
print last_quarter_minute
print current_time
Ideally, I want to be able to compare the time I get from a log, to the last quarter time.
You need to replace minute part of the time, using datetime.datetime.replace (returns a new datetime object with the specifieid field replaced):
>>> time.strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:57'
>>> time.replace(minute=last_quarter_minute).strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:45'
To be more precise, you need to also set second, microsecond also.

Getting a lists of times in Python from 0:0:0 to 23:59:59 and then comparing with datetime values

I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this.
So I need a list that has data like:
[00:00:00]
[00:00:01]
[00:00:02]
till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM.
Thanks!
Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way.
import datetime
now = datetime.datetime.now()
for h in xrange(24):
for m in xrange(60):
for s in xrange(60):
time_string = '%02d:%02d:%02d' % (h,m,s)
if time_string == now.strftime('%H:%m:%S'):
print 'you found it! %s' % time_string
Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.
There's a great answer on how to get a list of incremental values for seconds for a 24-hour day. I reused a part of it.
Note 1. I'm not sure how you're thinking of comparing time with datetime. Assuming that you're just going to compare the time part and extracting that.
Note 2. The time.strptime call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to time.strftime that returns a 24-hour-based time.
Here's what I think you're looking for:
my_time = '6/23/2011 6:38:00 AM' # time you defined
from datetime import datetime, timedelta
from time import strftime, strptime
now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)
times = []
while now <= last:
times.append(now.strftime('%H:%M:%S'))
now += delta
twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True

Categories

Resources