OperationFailure Unsupported projection option: endingDate - python

I am trying to get the document whose endingDate is greater or equal to currentDateTime and also fetching entityID.
{"_id":{"$oid":"5ecfba0b1191f2b87ee1ccd2"},
"entityId":"5ecfb9d9d654557162afd861",
"endingDate":{"$date":"2020-08-11T00:00:00.000Z"}
My query is:
cursor= list(db.collection.find({},{"entityId":1,
"endingDate":{"$gte":datetime.datetime.now().isoformat()}}))
But it giving me error.
OperationFailure: Unsupported projection option: endingDate: { $gte: "2020-08-11T19:28:06.677643" }
Edit 1:
I tried this query also
import datetime
from datetime import datetime
temp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
date_time_obj = datetime.strptime(temp, '%Y-%m-%d %H:%M:%S')
cursor=list(db.TrendAnalysisSystem_jobdata.find({},
{"entityId":1,"hashTags":1,"skillsRequired":1,
"specialization":1,"endingDate":{"$gte":date_time_obj}}))
still getting the same error

You put the find condition into the projection argument. Try:
cursor= list(db.collection.find({"endingDate": {"$gte":datetime.datetime.now().isoformat()}},{"entityId":1, }))

Related

Excel passing unrecognizable date format to python function in xlwings

I am trying to link a script to an excel file using xlwings that takes data from the sheet and queries skyscanners API to return flight prices. When I type dates in manually (yyyy-mm-dd), it works fine since it is a String. However, when I try to run the query by automatically loading the date from excel, it cannot work with excel's date format.
When I just return type(dept_date), I get the error: Unexpected Python Error: TypeError: must be a pywintypes time object (got type)"
When I try to convert dept_date to a string first and return that type, I get: Unexpected Python Error: TypeError: Objects of type 'type' can not be converted to a COM VARIANT.
For context, the API takes the yyyy-mm-dd format and when I print the querystring, excel automatically adds the "00:00:00" to the end of the date. I've tried subscripting [:9] to just pull the date but since it isn't a String, that doesn't work. I've tried casting to a string and doing that too with no luck. Any help is appreciated! I've included the whole function below just in case:
#xw.func
def airfare(trip_type, home_iata, dest_iata, dept_date, return_date=""):
""" Pass home IATA, destination IATA, departure/return dates (yyyy-mm-dd). Returns average of "best"
results. All params are strings. To account for last minute booking, if flight is < 500, result doubles.
If flight is 500+, it adds a 30% surcharge onto result. Trip type 1 = Round Trip; 0 = One-Way
"""
home_iata = str(home_iata)
dest_iata = str(dest_iata)
dept_date = str(dept_date)
# dept_date.strftime('%d-%m-%Y')
if trip_type == "0":
return_date = ""
url = "https://skyscanner44.p.rapidapi.com/search"
querystring = {"adults": "1",
"origin": home_iata,
"destination": dest_iata,
"departureDate": dept_date,
"returnDate": return_date,
"cabinClass": "economy",
"currency": "USD"}
headers = {
"X-RapidAPI-Key": "XXX",
"X-RapidAPI-Host": "skyscanner44.p.rapidapi.com"
}
# return querystring
# return type(dept_date)
response = requests.request("GET", url, verify=False, headers=headers, params=querystring).json()
best_flight = int(response["itineraries"]["buckets"][0]["items"][0]["price"]["raw"])
if best_flight < 500:
best_flight *= 2
else:
best_flight *= 1.3
return "$" + str(best_flight)

Timestamp is different in flutter from Firestore and Postman

In my app, when the user adds a document, I store the timestamp of the document creation.
My app calls an api written in Flask.
I store the timestamp in python with:
timestamp = firestore.SERVER_TIMESTAMP
The timestamp is stored in Firestore as:
When the user requests the document, I process the timestamp to be shown in a readable way with the following code:
def get_proper_timestamp(timestamp) -> str:
if not timestamp:
return None
date: datetime.date = timestamp.date()
day = str(date.day)
month = str(date.month)
year = str(date.year)
if len(month) == 1:
month = f"0{month}"
proper_date = f"{day} {month} {year}"
weekday: int = date.weekday()
proper_weekday: str = get_day_from_int(weekday)
time = timestamp.time()
hour = time.hour
minute = time.minute
temp = strptime(f"{hour}:{minute}", "%H:%M")
proper_time: str = strftime("%I:%M %p", temp)
return f"{proper_weekday}, {proper_date}.{proper_time}"
def get_day_from_int(integer: int) -> str:
mapper = {
0: "Mon",
1: "Tues",
2: "Wed",
3: "Thur",
4: "Fri",
5: "Sat",
6: "Sun",
}
return mapper[integer]
In Postman, this outputs:
My flutter code reads the timestamp in a straight-forward way:
List<DataCell> _buildCells(Map<String, dynamic> entry) {
String timestamp = entry["timestamp"];
print(timestamp);
return [
DataCell(Text(entry["timestamp"].toString())),
DataCell(Text(entry["amount"].toString())),
DataCell(Text(entry["after"].toString()))
];
}
This outputs:
This is four hours before. Which I think it means that I'm the UTF offset somewhere.
But why is Postman showing the date correctly?
I'd actually prefer flask to return the raw timestamp, but I couldn't deserialize it.
I read most the answers on SO on this issue, but nothing worked for me.
The value stored in Firestore is an internal structure, which is timezone agnostic (internally based on UTC).
The value you see in the Firestore console has been localized to your local timezone for your convenience, which is apparently UTC+4.
The value you get when fetching the time with Flutter is a Timestamp, also UTC-based and timezone agnostic. When you convert that with .toDate() (or the equivalent with millisecondsSinceEpoch), it becomes a traditional DateTime, which is internally in UTC, but carries a localtime offset, and normally displays itself as localtime. This is probably the value you are seeing as +4.

TypeError: Object of type 'datetime' is not JSON serializable, python

I am trying to write date-time to MongoDB from python.
time_second = ('{0}-{1}-{2} {3}:{4}:{5}.{6}{7}'.format(t_year, t_month, t_day, t_hour, t_minute, t_second, t_ms, t_us))
date = datetime.strptime(time_second, "%Y-%m-%d %H:%M:%S.%f")
date_json = json.dumps(date)
I am getting the TypeError:

Error - "SQLite DateTime type only accepts Python " "datetime and date objects as input."

I tried to declared a variable contains of Datetime like this
ts1.departure_date = '2012-03-03 10:10:10'
but then I got this error
StatementError: (exceptions.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
I wonder what is the correct way to declare a variable with datetime format? Thanks in advance
First import the datetime class:
from datetime import datetime
Then create a datetime object and use that to set your attribute:
ts1.departure_date = datetime(2012, 3, 3, 10, 10, 10)
expiration_year = int(form.expiration_date.data[:4])
expiration_month = int(form.expiration_date.data[5:7])
expiration_date = int(form.expiration_date.data[8:10])
expiration_date =datetime(expiration_year,expiration_month,expiration_date)
Ultra strange error that encountered with SQLAlchemy with both SQLite and Postgres
from datetime import datetime
....
#WORKS
lending_operation = models.LendingOperation(
device_id = device.device_id,
start_using = datetime.now()
)
db.session.add(lending_operation)
db.session.commit()
#DIDN'T WORK
lending_operation = models.LendingOperation(
currency = "USD",
device_id = device.device_id,
start_using = datetime.now()
)
db.session.add(lending_operation)
db.session.commit()
#MODEL: models.py
class LendingOperation(db.Model):
.....
start_using = db.Column(db.DateTime, default=datetime.now )
.....
currency = db.Column(db.DateTime)
Hope it helps, didn't find any info on the exception

Calculate Field to remove time from datetime Python

I want to calculate the value of a new field by grabbing the date only (strip out the time) from the existing field DATE_VAL.
I keep getting errors however. Here is my code.
formatter_string = "%m%d%y"
arcpy.CalculateField_management("joined", "Date", dt.strftime("!DATE_VAL!", formatter_string), "PYTHON_9.3", "")
If I try the following:
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
I get the following error:
ExecuteError: ERROR 000539: Error running expression: dt.strftime(u"5/1/2014 3:00:00 AM", formatter_string).date()
When I try the following:
formatter_string = "%m/%d/%Y %I:%M:%S %p"
arcpy.CalculateField_management("joined", "Date",
dt.strptime("!DATE_VAL!", formatter_string).date(), "PYTHON_9.3", "")
I get the error: ValueError: time data '!DATE_VAL!' does not match format '%m/%d/%Y %I:%M:%S %p'
datetime.datetime objects have a date method that will return a datetime.date object.
formatter_string = "%m/%d/%Y %I:%M:%S %p"
arcpy.CalculateField_management("joined", "Date",
"dt.strptime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
I found some code to use update cursor rather than the calculate field. This seems to work for my purpose. I probably should have posted this in the gis stack exchange. sorry.
arcpy.AddField_management("joined", "Date", "DATE")
rows = arcpy.UpdateCursor("joined")
for row in rows:
datetimeVal = row.getValue("DATE_VAL")
formattedTime = dt.strftime(datetimeVal, "%m/%d/%Y")
row.setValue("Date", formattedTime)
rows.updateRow(row)
del rows, row
Im not the arcpy guy but this should do:
Instead of:
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
Do this:
date_format = '%m/%d/%Y'
formatter_string = '%m/%d/%Y %I:%M:%S %p'
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date().strftime(date_format)", "PYTHON_9.3", "")

Categories

Resources