datetime compare time python - python

I have 2 events A and B. I have already created a function get_schedule(event) to get the date and time of A and B occurring in datetime.
For example:
get_schedule(a) -> datetime.datetime(2016, 1, 1, 2, 25)
How can I create a function to check if my event occurs before/after a certain timing irregardless of the date? I thought about slicing the time and comparing but I don't know how to go about it.

You can get just the time object by calling the datetime.time() method. Compare that to another time object:
# scheduled after 12 noon.
get_schedule(a).time() > datetime.time(12, 0)
Demo:
>>> import datetime
>>> datetime.datetime(2016, 1, 1, 2, 25).time()
datetime.time(2, 25)
>>> datetime.datetime(2016, 1, 1, 2, 25).time() > datetime.time(12, 0)
False

Related

Filter time array in python with datetime library

I want to filter my list of time string elements with the help of python datetime library.
I have a array like -
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
I want to make it be filtered from the ascending order (0:0:0 - 23:59:59) accordingly.
Also i will have bulk of data (array should be almost containing more than 5k ) so what will be most efficient for this?
How can i achieve this in python?
the resulting array should be something like -
["0:0:16","2:50:32","3:59:9","20:30:12","23:46:52"]
This will convert the strings to datetime, sort them then output a list with your desired format.
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
sorted(time_Arr, key=lambda x: datetime.strptime(x, '%H:%M:%S'))
['0:0:16', '2:50:32', '3:59:9', '20:30:12', '23:46:52']
Use datetime to parse the time then sort:
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
time_Arr = sorted([datetime.strptime(t, "%H:%M:%S") for t in time_Arr])
# [datetime.datetime(1900, 1, 1, 0, 0, 16),
# datetime.datetime(1900, 1, 1, 2, 50, 32),
# datetime.datetime(1900, 1, 1, 3, 59, 9),
# datetime.datetime(1900, 1, 1, 20, 30, 12),
# datetime.datetime(1900, 1, 1, 23, 46, 52)]
from datetime import datetime
sorted([datetime.strptime(time, "%H:%M:%S") for time in time_Arr])

Adding up datetime.datetime that are in single list

I've looked everywhere and I can't seem to find what I need. I have a list that contains datetime that I need to combine to find the sum. This list is parsed from a file and can have any number of datetime items in it. It looks like such for an example.
[datetime.datetime(1900, 1, 1, 1, 19, 42, 89000), datetime.datetime(1900, 1, 1, 2, 8, 4, 396000), datetime.datetime(1900, 1, 1, 0, 43, 54, 883000), datetime.datetime(1900, 1, 1, 0, 9, 13, 343000)]
The code I'm using to get this is this
time = [i[8] for i in smaller_list]
try:
times = [datetime.datetime.strptime(x, "%H:%M:%S.%f") for x in time]
except ValueError:
times = [datetime.datetime.strptime(x, "%M:%S.%f") for x in time]
Time gets the varibles from a larger nested list that I created to separate lines of data. I've tried datetime.datetime.combine() but I'm not really sure how to use this for items in a single list. Do I need to create a nested list of datetimes and sum them up? How do I iterate though this list and combine all the times for a sum? If I do have to create a nested list, how do I iterate through it to add up the times? Trying to wrap my head around this.
When you print time this is what is returned so the example list directly helps me.
[datetime.datetime(1900, 1, 1, 1, 19, 42, 89000), datetime.datetime(1900, 1, 1, 2, 8, 4, 396000), datetime.datetime(1900, 1, 1, 0, 43, 54, 883000), datetime.datetime(1900, 1, 1, 0, 9, 13, 343000)]
This is what the original times look like. I need to add up times such as these for total time. Usually in minutes with micro seconds included and rarely hours.
25:21.442
09:52.149
28:03.604
27:12.113
If anyone else runs into this problem here is the code I used.
time = [i[8] for i in smaller_list]
sumtime = datetime.timedelta()
for i in time:
try:
(h, m, s) = i.split(':')
d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=float(s))
except ValueError:
(m, s) = i.split(':')
d = datetime.timedelta(minutes=int(m), seconds=float(s))
sumtime += d
print(str(sumtime))
If you're learning python it's pretty confusing trying to wrap your mind around date time and time delta. For duration's you need to use timedelta. You have to split the values up and pass the correct values to time delta and then you can sum them up to find the duration. Hopefully this helps someone out there.
If you need to round the microseconds to seconds you can use this code in place of d.
d = datetime.timedelta(minutes=int(m), seconds=round(float(s)))

Python datetime library not able to handle 01022018 i.e as in MMDDYYYY format when left most zero is truncated

I have an issue that I am encountering with one of the modules. Due to the requirement of data handlers, one of the modules has to use the datetime library and the strptime function. But the code behavior does not seem to be consistent, when the left most zero from a date series in format MMDDYYYY is truncated especially for Jan month. Below are some example,you can see the 2nd and third command are identical but the month is getting corrupted. Anyways around how to handle it?
>>> datetime.strptime('01082018',"%m%d%Y")
datetime.datetime(2018, 1, 8, 0, 0)
>>> datetime.strptime('1082018',"%m%d%Y")
datetime.datetime(2018, 10, 8, 0, 0)
>>> datetime.strptime('8082018',"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)
>>> datetime.strptime('08082018',"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)
You can try to split it in two multiple commands and append a zero (if need be)
>>> date_str = '01082018'
>>> if len(date_str)==7:
>>> date_str = '0'+date_str
>>> datetime.strptime(date_str ,"%m%d%Y")
datetime.datetime(2018, 1, 8, 0, 0)
AND
>>> date_str = '8082018'
>>> if len(date_str)==7:
>>> date_str = '0'+date_str
>>> datetime.strptime(date_str ,"%m%d%Y")
datetime.datetime(2018, 8, 8, 0, 0)

Is there a direct way to ignore parts of a python datetime object?

I'm trying to compare two datetime objects, but ignoring the year. For example, given
a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:
c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?
I'm using python 3.4.
(a.month, a.day, a.hour, a.minute, a.second ==
b.month, b.day, b.hour, b.minute, b.second)
A less explicit method is to compare the corresponding elements in the time tuples:
a.timetuple()[1:6] == b.timetuple()[1:6]
Try:
a.replace(year=1,microsecond=0) == b.replace(year=1,microsecond=0)
You can also consider comparing formatted date strings consisting of the fields you wish to include in the comparison. This allows you to be somewhat explicit while using shortened versions of the fields (as opposed to accessing a.year, a.month, etc.).
from datetime import datetime
date_string = '%m %d %H %M %S'
a = datetime(2015, 7, 4, 1, 1, 1)
b = datetime(2016, 7, 4, 1, 1, 1)
print(a.strftime(date_string) == b.strftime(date_string)) # True
def cmp(a,b):
return (a > b) - (a < b)
d1=(2015,7,4,1,1,1)
d2=(2016,7,4,1,1,1)
cmp(list(d1)[1:],list(d2)[1:])
Returns 0 - they are the same, i.e. 0 differences
d1=(2015,7,4,1,1,1)
d2=(2015,2,4,1,1,1)
cmp(list(d1)[1:], list(d2)[1:])
returns -1, there is a difference.
In [70]: a
Out[70]: datetime.datetime(2015, 7, 4, 0, 0)
In [71]: b
Out[71]: datetime.datetime(2016, 7, 4, 0, 0)
In [72]: def my_date_cmp(a, b):
....: return a.replace(year = b.year) == b
....:
In [73]: my_date_cmp(a, b)
Out[73]: True

Convert a Date in String Format to a datetime.date

I have some strings which come to me in formats like
29-Jul-2014 or 03-Aug-2015
What is the easiest way to convert this to a datetime.date object?
I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...} and then do
dt = datetime.date(year, d[month], day)
Is there any other easier way and avoid the creation of this dictionary?
Thanks
Use datetime.datetime.strptime to convert the string to datetime.datetime object.
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)
Then, use datetime.datetime.date method to convert it to datetime.date object:
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
The easy way is use dateutil.parse module, it lets to parse the common date formats, even if you don't know what it is using currently
Ex:
>>> import dateutil.parser
>>>
>>> utc_time = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)
Once you have a datetime object, you only should invoke the datetime.date() method

Categories

Resources