almost a beginner
almost a beginner

Reputation: 1632

Manually set models.DateTimeField

I've created a Transaction table which I want to test, one of the most important field of this table is:

models.DateTimeField(
            default=timezone.now)

In order to test my app with the database, I need historical data. Currently when I create a transaction, it sets the date and time automatically, so it is always current.

I need previous month data and I'm wondering if I can manually set the above field when I create a transaction?

Upvotes: 2

Views: 1748

Answers (1)

bakkal
bakkal

Reputation: 55448

Currently when I create a transaction, it sets the date and time automatically

You can always override that default value before you save the model instance, for the example below let's assume your DateTimeField with the default value is called timestamp:

import datetime

transaction = Transaction()
transaction.timestamp = timestamp # Overrides the default
                                  # You can use a datetime.datetime 
                                  # instance as value
# transaction.timestamp = datetime.datetime(year, month, day, hour, minute, second)
transaction.save()

"Override" is a big word, since the default is only used when you don't provide a value.

and what is the format of the timestamp? is it timestamp = datetime (year, month, day, hour..)?

Yes the DateTimeField field will accept a datetime.datetime object.

Upvotes: 1

Related Questions