I want to create general custom field to read str dates and convert it to date with passed format.
So, I want something like this:
date_field = CustomDateField(format=custom_format)
Is it possible? I hope so
Related
I know there are so many questions and answers based on conversion of datetime field in python.
Here I am having a date field in the format like "2019-10-30T11:29:43+00:00", which is type string. I need to embed this value in to mongodb. Here the value is storing as a str in the database. I need this to be converted and store something like ISODate("2020-05-27T14:57:31.302Z").
So far I have tried is
date_iso = datetime.datetime.strptime(line['date_field'][:19], '%Y-%m-%dT%H:%M:%S');
date = date_iso.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
This returns the date in str type.
Note: This is python 2.7
class Test(Model):
time = DateTimeField()
# ...
row = Test.select()[0]
test.time
This returns a string that looks like this: 2017-01-23 01:01:39+01:00. How can I get it as a datetime object instead? Do I have to parse it manually?
Also I would be interested if there is any documentation on how to use the DateTimeField. The official documentation doesn't have anything on it.
Are you using SQLite? If so, SQLite doesn't have a dedicated datetime type, so datetimes are stored as strings in the DB. What peewee will do is recognize certain datetime formats coming out of the DB and convert them to datetime objects. What you need to do is ensure that either:
When you create/save your object, that you assign a datetime object to the field.
When reading back pre-existing data, that the data is in a recognized format.
The formats peewee supports out-of-the-box for datetime field are:
YYYY-mm-dd HH:MM:SS.ffffff
YYYY-mm-dd HH:MM:SS
YYYY-mm-dd
It looks like your has zone info. I'd suggest converting to UTC and dropping the zone info. That should fix it.
Have you tried adding a default like this?
time = DateTimeField(default=datetime.datetime.now())
Or when adding an entry add it as a datetime.datetime object directly:
test = Test(....., time=datetime.datetime.strptime("2018-3-15", '%Y-%m-%d'))
In the second case you don't need to specify anything in the class definition...
I am working on a form and have a date field.
I want to save different date format for date field instead django used.
I am getting "01-jan-2016" date and want to save as it is in my database.when i am trying to save this same format is raise an error
[u"'07-Dec-2016' value has an invalid date format. It must be in YYYY-MM-DD format."].
I know this type of question asked already but they do not solve my problem.
views.py
post_date = request.POST['date']
lead_obj = CustomerLeads.objects.create(posting_date = post_date)
my models.py
class Leads(models.Model):
customer_name = models.CharField(max_length=50,null=True, blank=True)
title = models.CharField(max_length=100, null=True, blank=True)
posting_date = models.DateField()
Mysql
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
Postgresql
Date and time input is accepted in almost any reasonable format,
including ISO 8601, SQL-compatible, traditional POSTGRES, and others.
For some formats, ordering of day, month, and year in date input is
ambiguous and there is support for specifying the expected ordering of
these fields. Set the DateStyle parameter to MDY to select
month-day-year interpretation, DMY to select day-month-year
interpretation, or YMD to select year-month-day interpretation.
The table at the link shows that postgresql accept the format that you are looking for. But how is it stored? Let's try an insert
INSERT INTO stackoverflow_heatwatchlist(next_date_from, next_date_to)
VALUES('1999 Jan 05','2001 Jun 06');
And when you select, what you get is '2001-06-06' and '1999-01-05'
SQlite
Here you can insert in any format you want and it will be saved exactly as you entered, that's because sqlite does not enforce any strict type checking. Types in sqlite are purely cosmetic. but django has a different opinion on the matter and will not let you divert too much from the standard formats.
SQL Server
A lot of flexibility in how the data is accepted for insert. Refer to the table at the link. But how is it stored? '1999-01-05'
In conclusion
How the date is stored in the table is totally irrelevent, all that matters is what formats are accepted for input and how it's displayed. And that's where django's and python's excellent date and time formats come into play.
If you are not happy with them, you have two choices. The first is to store dates and times as unix timestamps and do all the formatting yourself, all you need is a little math really - a fairly common practice.
The second is to use CharField for storing your data but this is not very usefull. Not only do you have to do all the formatting and input validation yourself, any calculation would involve a lot of string processing and casting.
Try to add '%d-%b-%Y' to DATE_INPUT_FORMATS in your project settings.
In your views.py try this:
from dateutil import parser
d = parser.parse("07-December-2016")
print d
d = d.strftime("%d-%b-%Y")
print d
Output:
2016-12-07 00:00:00
07-Dec-2016
It will handle various formats.
I want to save date in my django model into desired format.
post_date = str(request.POST['date'])
I am getting date from front end is 12/21/2016
i want to save this date in my django modal is like 21-Dec-2016.
How can i do it.
it will be good if you can provide some sample code.
Thanks in advance.
you want to store in DB string parameter? The easiest way convert input string to date and then convert from date to string. But of course it is more logical to store date format imho
I am making a blog and store the publishing date of a blog post in the datastore. It looks like this:
post.date = datetime.datetime.now()
It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can I set that how the date is displayed? I'd like to set the date format like in UNIX date function (like %Y/%m etc). I tried to add some parameters in my templates but that returned errors.
Thanks in advance!
-skazhy
I think strftime is the method you're looking for.
From the link:
>>> d.strftime("%d/%m/%y")
'11/03/02'
If you pass in the result of the strftime in your 'template_values' or similar (the dictionary you use to pass parameters to the template) instead of the actual date it will be displayed instead.
You can use .strftime() on a datetime object to do the formatting. See the relevant python documentation for details.