Compare two dates with different formats in Python - python

I'm not familiar with Python, just debugging an existing code. I'm comparing two dates here but they have different formats. I get the "TypeError: can't compare offset-naive and offset-aware datetimes" when I do the compare.
if date_start <= current_date:
"TypeError: can't compare offset-naive and offset-aware
str(date_start) >> 2015-08-24 16:25:00+00:00
str(current_date) >> 2015-08-24 17:58:42.092391
How do I make a valid date comparison? I'm assuming I need to convert one to another format.
UPDATE
hour_offset = 0
minute_offset = 0
if timezone_offset:
offset_sign = int('%s1' % timezone_offset[0])
hour_offset = offset_sign * int(timezone_offset[1:3])
minute_offset = offset_sign * int(timezone_offset[3:5])
current_date = (datetime.datetime.now() +
datetime.timedelta(hours=hour_offset,minutes=minute_offset))
The previous dev might have applied the timezone offset this way. Any thoughts on this one?

Use dt.replace(tzinfo=tz) to add a timezone to the naive datetime, so that they can be compared.

There is no more details here to solve.But if you want to get a offset-naive time.Try this
(offset-aware-datetime).replace(tzinfo=None)
To add a timezone to offset-naive time.Try this
(offset-naive-datetime).replace(tzinfo=tz)

One way is to convert the date to seconds since epoch and then compare. Say,if your date is 2015-08-24 16:25:00 then you can convert to seconds using datetime method. It takes parameters as (year, month, day[, hour[, minute[,second[, microsecond[, tzinfo]]]]]). It returns a datetime object. Finally, you can use strftime() to get seconds as a zero-padded decimal number. So your code can be:
import datetime
d1 = datetime.datetime(2015,8,24,16,25,0)
d2 = datetime.datetime(2015,8,24,17,58,42,92391)
if int(d1.strftime("%s")) > int(d2.strftime("%s")):
print "First one is bigger"
else:
print "Second one is bigger"
I hope this helps!

Related

How to remove date from datetime object

I have a method that converts a string to a datetime object using strptime("%I:%M %p"), I only want the hours in 24 and minutes without any dates, because I will get the difference between this time and another time. The problem is that when I try to get the difference with total_seconds(), it gets difference in negative because the date in the strptime is "1900-01-01". Does any one have any ideas how to solve this?
My Code:
fTime = datetime.strptime(time, "%I:%M %p")
if 0 < (fTime - datetime.now()).total_seconds() <= 3600:
return True
You can take one of two approaches: strip the date out of now, or add the current date to fTime. The first approach makes little sense, since you can't compare time objects like that anyway.
To convert fTime to a proper datetime, datetime.combine it with date.today():
fDate = datetime.combine(date.today(), fTime.time())
return 0 < (fDate - datetime.now()).total_seconds() <= 3600
Alternatively, you can replace the date portion:
today = date.today()
fDate = fTime.replace(year=today.year, month=today.month, day=today.day)
Personally, I would go with combine because it's less awkward code.

Get the average number of days between two dates in Python

I have a data frame with only dates in one column.
My objective is to calculate the number of days between each date, in order to get the average number of days between two dates (each date corresponds to an operation).
I tried doing something like this :
for i in range(len(df)):
if i != 0:
d0 = df.iloc[[i-1,1]]
d1 = df.iloc[[i,1]]
L.append((d1 - d0).days)
But got the error message : 'unsupported operand type(s) for -: 'str' and 'str''
You can subtract a date from another if they're in proper format. Maybe a timestamp in seconds, maybe a proper datetime object. As you might've noticed, you can't subtract strings.
If the date is in the ISO format, it's the easiest, just do this before the subtraction:
from datetime import datetime
d0 = datetime.fromisoformat(d0)
d1 = datetime.fromisoformat(d1)
The result will be in a datetime.timedelta format with a .total_seconds() method and even a .days attribute, so you get days like this:
difference_in_days = (d1 - d0).days
If it's something else than an ISO string, check out this question:
Converting string into datetime

Want to find difference, in days, between two dates, of different date format, in Python

I have two different dates that I am pulling from a database using a SQL query. Im looking to do transformations in Python, but the two main dates I want to work with are stored in different formats. The first date is of the date format (YYYY/MM/DD) the other is of (YYYY/MM/DD HH:MM:SS) format. I want a difference in days so the DATETIME is irrelevant on the second date. I was wondering what is the easiest way to do this in python? Ideally, I would like to automate this, where I create a DATE format of the DATETIME variable, and take the difference between the two DATES.
I've tried the following but I am also getting errors since I am dealing with Series. I am trying to get the delta for every row.
df.delta = (df.DATETIME - df.DATE)
and
df.delta = datetime.timedelta(df.DATETIME - df.DATE)
import datetime
d1 = datetime.datetime.strptime('2018/01/13', '%Y/%m/%d')
d2 = datetime.datetime.strptime('2018/01/15 18:34:02', '%Y/%m/%d %H:%M:%S')
delta = d2 - d1
print delta.total_seconds()
print delta.days
Convert your datetime object to a date object, you are then able to subtract them for a delta value.
df.delta = (df.DATETIME.date() - df.DATE)

Time difference with different time formats in Python3

Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser
I'm not sure what I need to do to parse them into the same format, but my two dates are:
2017-05-24 15:40:00+00:00
2017-05-24 14:23:44.995015
If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?
Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?
import dateutil.parser
date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
date_delta = date1 - date2 # 1:16:15.004985
You can call replace(microsecond=0) on your dates to remove the microseconds.
You could transform the second datetime (that is a timestamp) into the first one with this code:
def convert_to_timestamp(string_date):
the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
or:
def transformTimestamps(timestamp_):
year = timestamp_[:4]
month = timestamp_[4:6]
day = timestamp_[6:8]
hour = timestamp_[9:11]
minute = timestamp_[11:13]
second = timestamp_[13:15]
microsecond = timestamp_[16:22]
myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
Then, you can calculate the difference between them.
I hope this help. Greetings!
Probably you want to use this method
datetime.strptime(date_string, format)
Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in
class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None, *, fold=0)
For more on this topic you can always read the python docs, you can find the same information I just gave you and more here:
https://docs.python.org/3/library/datetime.html
Hope it helped.

How to compare dates in Python?

I need to see if a date has more than X days. How can I do this in Python?
I have tested something like:
if datetime.date(2010, 1, 12) > datetime.timedelta(3):
I got the error:
TypeError: can't compare datetime.date to datetime.timedelta
Any clue on how to achieve this?
You can't compare a datetime to a timedelta. A timedelta represents a duration, a datetime represents a specific point in time. The difference of two datetimes is a timedelta. Datetimes are comparable with each other, as are timedeltas.
You have 2 options:
Subtract another datetime from the one you've given, and compare the resulting timedelta with the timedelta you've also given.
Convert the timedelta to a datetime by adding or subtracting it to another datetime, and then compare the resulting datetime with the datetime you've given.
Comparing apples and oranges is always very hard! You are trying to compare "January 12, 2010" (a fixed point in time) with "3 hours" (a duration). There is no sense in this.
If what you are asking is "does my datetime fall after the nth day of the month" then you can do :
my_important_date = datetime.now()
if my_important_date.day > n:
pass #do you important things

Categories