Python's datetime: "AttributeError: type object 'datetime.date' has no attribute 'strptime'" - python-datetime

I'm trying to convert a string date_str = '01-01-2000' to a date object, and want to compare with a given date.
I used my_date = datetime.datetime.strptime(date_str, "%d-%m-%Y") which works, until I try to compare with a given date:
if my_date <= other_date:
TypeError: can't compare datetime.datetime to datetime.date
When I change datetime to date and do datetime.date.strptime(date_str, "%d-%m-%Y"), I get AttributeError: type object 'datetime.date' has no attribute 'strptime':
datetime.date.strptime(date_str, "%d-%m-%Y")
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: type object 'datetime.date' has no attribute 'strptime'

There indeed is no strptime() for a datetime.date object, and there is no strpdate() function either.
Just use datetime.strptime() and convert to a date object afterwards:
my_date = datetime.datetime.strptime(date_str, "%d-%m-%Y").date()

Related

When mapping on an ActiveRecord query, my date object stored in the db is converted to a string

I'm trying to use ActiveRecord's date.beginning_of_day but when I'm mapping the query I want to use that method for, the Date obj is being converted to a string.
Here's the code snippet:
...
array = where(max_temperature: range).all.map {|condition| condition.date}
trip_nums = array.map do |date|
Trip.where(start_date: date.beginning_of_day...date.end_of_day).count
end
...
I found this when prying into that scope:
pry(Condition)> date.class
=> String
And when I check the class within tux:
>> Trip.first.start_date.class
=> Date
What is going on here?
EDIT: For context, I have a trips table with a start_date column assigned as a Date type
Found the error. The date in my conditions table was set as a string type.

Return Hash Date Value

I have an hash like this: value = {Fri, 14 Oct 2016=>58.0}
How to return the date's value which is 58.0?
Not much help from the docs.
Have tried value["#{DateTime.now}"] but that returns 0.
If that key is a date object try
value[Date.new(2016, 10, 14)]
If your key is a DateTime object you should do value[date_object]. So, if you created your hash like:
key = DateTime.now
value = {key=>58.0}
You should access it like: value[key]
If you know the string representation of that DateTime object, you can always convert it to DateTime by using the strptime method

ASP.NET MVC 3 Razor DateTime.Parse don't work

I'm trying to do a cast with dates but it's throws me an exception
.
The code is:
This Works ->
var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
This Doesn't Work ->
var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
The model is Ok and values are dates in string format
The error is:
Server Error in '/' Application.
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
Source Error:
Line 13: var Ubicacion = Model != null ? Model.Ubicacion : null;
Line 14: var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
Line 15: var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
The error is straight-forward. The string being passed to Parse could not be interpreted as a valid DateTime. By default, the format of the current culture is employed, when using Parse. Not sure what that is exactly in your case, but it would likely be the same as you would see by outputting DateTime.Now.ToString().
The reason DateTime.Today.ToString() failed, is because the output will only have a date component. The default format utilized by Parse will require date and time components.
If you need to parse a string into a DateTime that doesn't match the format of the current culture, then you need to use ParseExact instead of Parse and pass a format string that shows how the string-based datetime is formatted.

Laravel - convert input date format before save

I'm trying to convert date input to the proper mysql format.
My start_date field is formatted MM dd, yyyy.
In my controller store function I'm grabbing all the users input including start_date and saving.
$userProfileData->save();
What I thought I could do is us Carbon to convert the start_date before save like this.
$userProfileData->start_date->toDateString();
I get a Call to a member function toDateString() on a non-object error.
I was able to convert the date format by adding this to my users controller store function.
$userProfileData->start_date = date('Y-m-d', strtotime($userProfileData->start_date));
you get non-object error because start_date is not the object with method toDateString()
what you can do is use setStartDateAttribute() method in your model which will be invoked every time to get the start_date attribute value and in this method you can modify value so model will use the updated value for operation like edit or update it can be as follow
public function setStartDateAttribute($value) {
$this->attributes['start_date'] = date('Y-m-d', strtotime($value) );
}
the following method will used by your model when it needs to get the value of start_date attribute this method must be written in the model

How do I extract the created date out of a Mongo ObjectID

I'm using the Mongo shell to query my Mongo db. I want to use the timestamp contained in the ObjectID as part of my query and also as a column to extract into output. I have setup Mongo to create ObjectIDs on its own.
My problem is I can not find out how to work with the ObjectID to extract its timestamp.
Here are the queries I am trying to get working. The 'createdDate' field is a placeholder; not sure what the correct field is:
//Find everything created since 1/1/2011
db.myCollection.find({date: {$gt: new Date(2011,1,1)}});
//Find everything and return their createdDates
db.myCollection.find({},{createdDate:1});
getTimestamp()
The function you need is this one, it's included for you already in the shell:
ObjectId.prototype.getTimestamp = function() {
return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
}
References
Check out this section from the docs:
Extract insertion times from _id rather than having a separate timestamp field
This unit test also demostrates the same:
mongo / jstests / objid6.js
Example using the Mongo shell:
> db.col.insert( { name: "Foo" } );
> var doc = db.col.findOne( { name: "Foo" } );
> var timestamp = doc._id.getTimestamp();
> print(timestamp);
Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time)
> printjson(timestamp);
ISODate("2011-09-07T08:37:37Z")
This question is helpful to understand of how to use the _id's embedded timestamp in query situations (refers to the Mongo Extended JSON documentation). This is how it's done:
col.find({...,
'_id' : {'$lt' : {'$oid' : '50314b8e9bcf000000000000'}}
})
finds documents created earlier than the one that's given by oid. Used together with natural sorting and limiting you can utilize BSON _ids to create Twitter-like API queries (give me the last OID you have and I'll provide twenty more)
In python you can do this:
>>> from bson.objectid import ObjectId
>>> gen_time = datetime.datetime(2010, 1, 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)
>>> result = collection.find({"_id": {"$lt": dummy_id}})
I think, ObjectId.from_datetime() - its a useful method of standard bson lib
Maybe other language bindings have alternative builtin function.
Source: http://api.mongodb.org/python/current/api/bson/objectid.html
To use the timestamp contained in the ObjectId and return documents created after a certain date, you can use $where with a function.
e.g.
db.yourcollection.find( {
$where: function() {
return this._id.getTimestamp() > new Date("2020-10-01")
}
});
The function needs to return a truthy value for that document to be included in the results. Reference: $where
Mongo date objects can seem a bit peculiar though. See the mongo Date() documentation for constructor details.
excerpt:
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date(<integer>) specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

Resources