Select DataFrame rows between two dates

|

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

I am creating a DataFrame from a csv as follows:

stock = pd.read_csv("data_in/" + filename + ".csv", skipinitialspace=True)

The DataFrame has a date column. Is there a way to create a new DataFrame (or just overwrite the existing one) which only contains rows with date values that fall within a specified date range or between two specified date values?

👻 Read also: what is the best laptop for engineering students?

Select DataFrame rows between two dates date_range: Questions

How do I filter query objects by date range in Django?

2 answers

I"ve got a field in one model like:

class Sample(models.Model):
    date = fields.DateField(auto_now=False)

Now, I need to filter the objects by a date range.

How do I filter all the objects that have a date between 1-Jan-2011 and 31-Jan-2011?

299

Answer #1

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

Or if you are just trying to filter month wise:

Sample.objects.filter(date__year="2011", 
                      date__month="01")

Edit

As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

299

Answer #2

You can use django"s filter with datetime.date objects:

import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
                                sampledate__lte=datetime.date(2011, 1, 31))

We hope this article has helped you to resolve the problem. Apart from Select DataFrame rows between two dates, check other date_range-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Chen Innsbruck

Vigrinia | 2022-12-03

Maybe there are another answers? What Select DataFrame rows between two dates exactly means?. Checked yesterday, it works!

Marie Richtgofen

New York | 2022-12-03

I was preparing for my coding interview, thanks for clarifying this - Select DataFrame rows between two dates in Python is not the simplest one. Will get back tomorrow with feedback

Julia Lehnman

California | 2022-12-03

Thanks for explaining! I was stuck with Select DataFrame rows between two dates for some hours, finally got it done 🤗. Will use it in my bachelor thesis

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically