NeoWang
NeoWang

Reputation: 18513

Datetime string doesn't match after strftime() and strptime()

In a Django project, I store a Datetime Field in database. I get the date string from web page, and use datetime.strptime() to convert to datetime type, and assign it to the DatetimeField. But when I get the field and use strftime to get the string, it is one day off, why is this happening?

datestr = "2013-12-12";
expireDate = datetime.strptime(datestr, "%Y-%m-%d");
datamodel.time = expireDate;
datamodel.save();

# when I get the model in another method
expireDate = datamodel.time;
datestr = expireDate.strftime("%Y-%m-%d"); # I get "2013-12-11"

I think maybe it has something to do with timezone, but have no idea how to resolve it. Please help!

Upvotes: 0

Views: 653

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

You are storing datetime objects, not just a date. This means that the time is set to midnight in your local timezone. Retrieving the datetime object again does so in the UTC timezone instead, which is 6 hours off for you.

Store the datetime object with a timezone:

from django.utils.timezone import utc

datestr = "2013-12-12"
expireDate = datetime.strptime(datestr, "%Y-%m-%d")
datamodel.time = expireDate.replace(tzinfo=utc)
datamodel.save()

If you are handling just dates, you could also switch to using a DateField instead of DateTimeField:

datestr = "2013-12-12"
expireDate = datetime.strptime(datestr, "%Y-%m-%d").date()

date objects have no timezone associated with them.

Upvotes: 6

Related Questions