What i'm trying to do is to add one extra day to today's date and have the outcome match this formula "%Y-%m-%d" and nothing else. I want the printed results to match this yyyy-mm-dd
from datetime import datetime, timedelta, date
s = date.today()
date = datetime.strptime(s, "%Y-%m-%d")
modified_date = date + timedelta(days=1)
datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)
You are trying to do date operations on strings and not using the result of your formatting call:
s = date.today()
modified_date = s + timedelta(days=1)
modified_date = modified_date.strftime("%Y-%m-%d") # this would be more common
# modified_date = datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)
Related
I have a program that scrapes through an API and gets the required values from the fields. There is a field called published_date one act json object. I want to publish only the values for the last 2 months from current date.
try:
price = str(price).replace(',', '')
price = Decimal(price)
if date < end:
if not math.isnan(price):
report_item = PriceItem(
source=SOURCE,
source_url=crawled_url,
original_index_id=original_index_id,
index_specification=index_specification,
published_date=date,
price=price.quantize(Decimal('1.00'))
)
yield report_item
except DecimalException as ex:
self.logger.error(f"Non decimal price of {price} "
f"found in {original_index_id}", exc_info=ex)
The published date is extracted:
for report_date in REPORT_DATE_TYPES:
if report_date in result:
date = result[report_date].split(' ')[0]
date = datetime.strptime(date, '%m/%d/%Y')
MAX_REPORT_MONTHS = 3
current_date = datetime.now()
current_date_str = current_date.strftime('%m/%d/%Y')
start = datetime.strptime(current_date_str, '%m/%d/%Y')
last_date = current_date - relativedelta(months=MAX_REPORT_MONTHS)
last_date_str = last_date.strftime('%m/%d/%Y')
end = datetime.strptime(last_date_str, '%m/%d/%Y')
The above I say last date string and current date string.
Extract of the api:
After having gathered the data into a dataframe you can convert the column containing the dates to datetime and then through comparison operators mantain just the desidered data.
For example, assuming this is your data:
data = {'date': ['02/02/2022 10:23:23', '09/23/2021 10:23:23', '02/01/2021 10:23:23', '12/15/2021 10:23:23'], 'random': [324, 231, 213, 123]}
df = pd.DataFrame(data)
# convert date column to datetime
df['date'] = pd.to_datetime(df['date'], format="%m/%d/%Y %H:%M:%S")
# select "threshold" date, two months before current one
current_date = datetime.now()
last_date = current_date - relativedelta(months=2)
# select data published after last_date
df[df['date'] > last_date]
If we consider the date of today we will have this result.
Before:
date random
0 02/02/2022 10:23:23 324
1 09/23/2021 10:23:23 231
2 02/01/2021 10:23:23 213
3 12/15/2021 10:23:23 123
After:
date random
0 2022-02-02 10:23:23 324
3 2021-12-15 10:23:23 123
I want to receive only the hour part or minute part in django. Right now i'm using remindTime = request.POST.get("remindTime") to get the time but I only want the hour or minute or day or month. How can I do that?
here is the model
class Reminder(models.Model):
remindTime = models.DateTimeField(auto_now_add=False, auto_now=False)
how I get the time
if request.method == "POST":
remindTime = request.POST.get("remindTime")
Ty!
First, convert your string object to Datetime object:
my_string = '2019-10-31'
# Create date object in given time format yyyy-mm-dd
my_date = datetime.strptime(my_string, "%Y-%m-%d")
print(my_date)
print('Type: ',type(my_date))
Output:
2019-10-31 00:00:00 Type:
Second, step get your hour and minute:
print('Month: ', my_date.month) # To Get month from date
print('Year: ', my_date.year) # To Get month from year
Output:
Month: 10 Year: 2019
How to import a date from view and calculate the number of days remaining for another date?
Here is the solution I tried but it's not working:
class saisir_soumi(osv.osv):
_name='saisir.soumi'
def compa_date(self,cr,uid,ids,args,fields,context=None):
r = {}
date_format = "%D/%M/%Y"
joining_date = 'date_depot'
current_date = '29/04/2016 02:02:02'# current date
d1 = datetime.strptime(joining_date, date_format)
d2 = datetime.strptime(current_date, date_format)
diff = current_date - datetime.date.today()
return diff.days
_rec_name = 'NumOffre'
_columns = {
'NumOffre' : fields.char('N° Offre',required=True),
'organisme_s' : fields.char('Organisme',required=True),
'date_depot' : fields.datetime('Date dépot de soumission'), # the date to be seized and used for its difference with current date( today)
'jrestant': fields.function(compa_date,string='Jours restant')
}
_sql_constraints = [
('uniq_NumOffre', 'unique(NumOffre,id)', "numero offre doit resté unique !"),
]
you have to do it properly:
specify correct date/time format
parse datetime from string
substract the same data types: datetime - datetime
Code:
In [68]: current_date = '29/04/2016 02:02:02'
In [69]: date_format = '%d/%m/%Y %H:%M:%S'
In [70]: (datetime.datetime.strptime(current_date, date_format) - datetime.datetime.now()).days
Out[70]: 5
Extending from the question here, where queryset is filtered using input from the user, I wanted to know if it was possible to filter queryset depending on present month and week. Eg each month should start on the 1st and each week on a monday and the queryset should be filtered for all the tests that have taken place in the present month and week.
models.py
class City(models.Model):
city_name=models.CharField(max_length=100,default='',blank=False)
class Person(models.Model):
title = models.CharField(max_length=3,default="mr",blank=False)
name = models.CharField(max_length=50,default='',blank=False)
address = models.CharField(max_length=200,default='',blank=False)
city = models.ForeignKey(City)
class Test(models.Model):
person = models.ForeignKey(Person)
date = models.DateTimeField(auto_now_add=True)
test_name = models.CharField(max_length=200,default='',blank=False)
subject = models.CharField(max_length=100,default='')
views.py
def personlist(request, id):
data = requests.get('http://127.0.0.1:8000/app/cities/' + id + '/persons/').json()
context = RequestContext(request, {
'persons': data['results'],'count': data['count'],
})
return render_to_response('template.html', context)
And the related json
According to this question - one way could be to use
startdate = date.today()
enddate = startdate + timedelta(days=6)
Sample.objects.filter(date__range=[startdate, enddate])
But wouldn't date.today() keep changing everyday and thus everyday a new week will start and thus, a new queryset?Similarly with month. Is there a way to get querysets filtered by present week and month. With each starting from every monday and every 1st respectively?
You can use the __month and __year lookups to limit the queryset to this month's objects.
from datetime import date
today = date.today()
this_month_qs = Sample.objects.filter(
date__month=today.month,
date_year=today.year,
)
To find this weeks objects, you first need to find the date of this Monday. You can do this by finding today's day of the week (Monday = 0, Sunday = 6) using a date's weekday() method, and subtracting that many days from today. It's easy to calculate the last day of the week by adding 6 days, and then you can use __range to find this week's objects.
from datetime import date, timedelta
today = date.today()
# Use today.isoweekday() if you want the week
# to start on Sunday instead of Monday
first_day_of_week = date.today() - timedelta(today.weekday())
end_date = first_day_of_week + timedelta(days=6)
this_week_qs = Sample.objects.filter(date__range=[startdate, enddate])
I have a code :
def set_date_range_filter(self,attribute = None,start_date = None , end_date = None):
if attribute is None:
return
#Make sure set the passing start date and end date
if not start_date or not end_date :
return
if isinstance(start_date, str) :
start_date = datetime.strptime(start_date, "%Y-%m-%d")
if isinstance(start_date, unicode) :
start_date = datetime.strptime(str(start_date), "%Y-%m-%d")
if isinstance(end_date ,str):
end_date = datetime.strptime(end_date, "%Y-%m-%d")
if isinstance(end_date ,unicode):
end_date = datetime.strptime(str(end_date), "%Y-%m-%d")
# Shphnx Range Filter ,start_date and end_date must be integers that define the acceptable attribute values range
start_date = int(time.mktime(start_date.timetuple()))
end_date = int(time.mktime(end_date.timetuple()))
if start_date > end_date :
return
self.sphinx.SetFilterRange(str(attribute),start_date,end_date)
I want to update this code to accept only 'start_date' or only 'end_date' or both.
Like i want all date from 2014-01-01 or i want all data after 2014-01-01
or say i want all data from 2014-01-01 to 2014-09-01. how can i archive this ??
Rather than
if not start_date or not end_date :
return
replace with say
if not start_date:
start_date = '1971-01-01'
if not end_date:
end_date = '2037-01-01'
Or similar. If either are missing, then just use a very early, or very late dates (outside the range of your data). Example dates above choosen within range of unix timestamps.
(will then be turned into proper date objects via strptime)