In this blog post, we will explore how to use Date and Time fields in Peewee, a simple yet powerful Object-Relational Mapping (ORM) library for Python. Peewee makes it easy to work with databases, including handling various types of data fields, such as dates and times.
Setting up Peewee
Before diving into date and time fields, let’s quickly go over how to set up Peewee and connect it to a database.
First, install the Peewee library by running the following command:
pip install peewee
Next, import the necessary modules and set up a database connection:
from peewee import *
db = SqliteDatabase('mydatabase.db')
Replace 'mydatabase.db'
with the path and name of your database file.
Using the DateField
The DateField in Peewee allows us to store and manipulate dates in our database. Let’s say we have a Person
model that has a birth_date
field:
class Person(Model):
name = CharField()
birth_date = DateField()
class Meta:
database = db
To create a new Person
and save it to the database, we can use the create
method:
Person.create(name='John Doe', birth_date=date(1990, 1, 1))
Note that we need to import the date
class from the datetime
module to create a date
object.
To query for Person
records based on their birth dates, we can use the where
method:
query = Person.select().where(Person.birth_date == date(1990, 1, 1))
This will return all Person
records with a birth date of January 1, 1990.
Using the TimeField
Similarly, Peewee provides a TimeField to store and manipulate time values. Let’s add a meeting_time
field to our Person
model:
class Person(Model):
name = CharField()
birth_date = DateField()
meeting_time = TimeField()
class Meta:
database = db
To create a new Person
and set their meeting time, we can use the create
method:
Person.create(name='John Doe', birth_date=date(1990, 1, 1), meeting_time=time(9, 30))
Here, we import the time
class from the datetime
module to create a time
object.
To query for Person
records based on their meeting times, we can use the where
method:
query = Person.select().where(Person.meeting_time >= time(9, 0), Person.meeting_time <= time(10, 0))
This will return all Person
records with a meeting time between 9:00 AM and 10:00 AM.
Conclusion
Peewee’s DateField and TimeField make it easy to work with dates and times in your database using Python. By leveraging these fields, you can store, query, and manipulate temporal data with ease. Peewee’s simplicity and flexibility make it a great choice for working with databases in Python.
To learn more about Peewee and its various features, check out the official documentation.
Happy coding!