Django and Python handle changing date format
Im importing r开发者_Python百科ecords from a CSV file into a django model. The CSV file is uploaded by the user. The problem I'm facing is with the date field.
The date field expects the date to be in YYYY-MM-DD
but different spreadsheet programs default to different types of formats and I dont want the user to have to change their default format.
So I want to find the best method for django to accept dates that could possibly be in various formats.
What I thought could work is to specify a list of allowed date formats and try and match the string to one of them... thanks
The best option I've seen for "fuzy" date string parsing is the dateutil library.
Unfortunately, there are still possible cases where things will be ambiguous and any code will sometimes guess wrong. Dateutil has their matching logic pretty well documented tho, so should you run into wrong guesses you should be able to figure out what happened relatively quickly.
When you convert the date string into a datetime
object, you'll likely use datetime.strptime
with the format argument. I would ask the user what format they use and/or store it in the database (and by that I mean allow them to choose the format they want).
精彩评论