Equating python datetimes - python

I am working with a few slightly different styles of python datetimes. Problem is, I'd like to be able to equate them and I can't. From the database, I am getting datetimes in the format of:
datetime.date(2010, 11, 15)
Which, when returned, outputs:
2010-11-15
However, on my end, I need to turn some dates in a csv file into a date time. I do so by using the datetime.datetime.strptime package. So, here my code looks like this:
date = '11/15/2010' #The format in the CSV file
date = date.replace('/', ' ')
date2 = datetime.datetime.strptime(date, '%m %d %Y')
However, date2, when printed, outputs:
2010-11-15 00:00:00
And the two dates, though actually equivalent, won't evaluate to True when I throw a == in between them. Is there a way to use datetime.datetime.strptime to leave out hours, minutes, seconds? I'd like to conform to the format used in the first example (my database). Thanks

You're trying to compare a datetime and a date. To compare them, simply do:
date2.date() == datetime.date(2010,11,15)
and you should be fine.
A bit more context:
In [1]: import datetime
In [2]: datetime.date.today()
Out[2]: datetime.date(2013, 10, 28)
In [3]: datetime.datetime.now()
Out[3]: datetime.datetime(2013, 10, 28, 11, 5, 43, 997651)
In [4]: datetime.datetime.now() == datetime.date.today()
Out[4]: False
In [5]: datetime.datetime.now().date() == datetime.date.today()
Out[5]: True

Related

conditional python; Time format newer than 30 minutes

I have a variable that has a stored created date as:
2022-09-01T19:40:17.268980742Z
In python, if i wanted to look at that time and say if 'created' is within than the last 30 minutes, do X.
EDIT
I have another command I can use (working within Palo XSOAR), that will give me the current date time in ISO.
So really want I'm trying to do is say:
if created is within the last 30 minutes:
do X
Assume I have to capture current time as ISO variable (can do)
Set a variable less than 30 minutes of the current time (not sure)
then if create time is between those two values do X (not sure)
Any help is appreciated -
Thanks,
You can use datetime.now() to get the current datetime. We can then coerce your datetime string into a datetime object, too. Then, we can look at the difference and apply some logic.
import datetime
some_string = '2022-09-01T19:40:17.268980742Z'
some_string = some_string.split('.')[0]
timestamp = datetime.datetime.fromisoformat(some_string)
current_time = datetime.datetime.now()
if (current_time - timestamp) < timedelta(minutes=30):
print('x')
else:
print('y')
Here are how the variables look:
>>> print(timestamp)
datetime.datetime(2022, 9, 1, 19, 40, 17)
>>> print(current_time)
datetime.datetime(2022, 9, 5, 4, 26, 14, 345147)
>>> print(current_time - timestamp)
datetime.timedelta(days=3, seconds=31557, microseconds=345147)
Note, I wasn't able to convert the provided timestamp of 2022-09-01T19:40:17.268980742Z to a datetime object using the fromisoformat. Trimming down the microseconds six decimal places worked fine, but seven throws an error. This is expected for datetime objects as the permissable resolution is Between 0 and 999999 inclusive (src: https://docs.python.org/3/library/datetime.html).
This is why I split the string.
Works:
some_string = '2022-09-01T19:40:17.268980'
timestamp = datetime.datetime.fromisoformat(some_string)
Error:
some_string = '2022-09-01T19:40:17.2689801'
timestamp = datetime.datetime.fromisoformat(some_string)

compare date and time objects and get older date in python

I have 3 dates (in hours and sec and mins)
2016-11-30T13:27:04-05:00
2016-11-30T13:27:41-05:00
2017-03-01T22:16:35-05:00
How can i get older date which is 2016-11-30T13:27:04-05:00
as output
This python script is not giving correct results
import time
find_a = min(a)
print find_a
Try this
dat = ['2016-11-30T13:27:04-05:02', '2016-11-30T13:27:41-05:02','2016-11-30T13:27:04-05:00']
print(min(dat))
You can use dateutil.parser to parse dates and a min to compare them. Here is an example:
In [1]: from dateutil.parser import parse
In [4]: dates = ['2016-11-30T13:27:04-05:00', '2016-11-30T13:27:41-05:00', '2017-03-01T22:16:35-05:00']
In [5]: min([parse(s) for s in dates])
Out[5]: datetime.datetime(2016, 11, 30, 13, 27, 4, tzinfo=tzoffset(None, -18000))
a = ['2016-11-30T13:27:04-05:00', '2016-11-30T13:27:41-05:00','2017-03-01T22:16:35-05:00']
>>> min(a) '2016-11-30T13:27:04-05:00
It works, just try it as normal strings. You can avoid importing time
Do you want to convert them datetime objects and then find the minimum?
use the method specified here https://stackoverflow.com/a/12282040/5334188 to datetime objects and find minimum

Converting dates in Python

I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!

Python date check

I'm hoping to create a program that takes todays date and a given date in the future and finds the difference in days between those two dates. I'm not too sure as to how I would go about doing this and I have very little experience using datetime.
From what I've been trying and reading up, I need to import datetime, and then grab todays date. After that, I need to take an input from the user for the day, month and year that they want in the future, and to make a check that the current year is less than the future year. After that, I'll need to do a calculation in the difference in days between them and print that to the screen.
Any help would be very much appreciated.
Many Thanks
here a hint for you small program using datetime and time:
>>> import time
>>> import datetime
>>> today_time = time.time()
>>> today_time
1415848116.311676
>>> today_time = datetime.datetime.fromtimestamp(today_time)
>>> today_time
datetime.datetime(2014, 11, 13, 8, 38, 36, 311676)
>>> future_time = input("Enter Year,month,day separeted by space:")
Enter Year,month,day separeted by space:2015 06 24
>>> year,month,day = future_time.split()
>>> diff = datetime.datetime(int(year),int(month),int(day)) - today_time
>>> diff.days
222
you can use datetime.date but instead asking user current date, you can have it from the system using time.time

Convert strange date format to standard date format

In Sweden we sometimes use a strange date format, for example New Year is the 31/12. If I have this format as a string ,which can be any date between 1/1 and 31/12, and if we assume that it is this year, how do I get into a standard date format using Python (format as 2012-01-01 and 2012-12-31) that can be sore in be stored as a date in a mySQL database.
Simply split the two values, map them to integers and update a datetime.date() instance:
import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)
By using datetime.date.today() we get the current year.
Demo:
>>> import datetime
>>> somevalue = '31/12'
>>> day, month = map(int, somevalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 12, 31)
>>> someothervalue = '1/1'
>>> day, month = map(int, someothervalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 1, 1)
Alternatively, you could use the datetime.strptime() method to parse these dates, but you'll have to manually correct the year afterwards (it'll use 1900 as the default if no year is being parsed):
adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)
There is nothing strange about this format :)
You can use the datetime module:
import datetime
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012)
print d
>> datetime.date(2012, 12, 31)

Categories