Convert string to datetime in django? - python

i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python?

If you absolutely must do this, use time.strptime. It would be a better idea not to store structured data in a string if you can avoid it, though.

Within Django's templates you can use the date Template Filter:
{{ value|date:"h:i:s a" }} # '18:30:00' would appear as 6:30:00 p.m.
{{ value|date:"g:i:s a" }} # '18:30:00' would appear as 06:30:00 p.m.
value would be the string variable you pass in the Context to the Template when you render it. The string appearing after date: formats the time.
You can find more here: http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#date
Hank Gay's answer is more correct than mine; you should avoid keeping structured data in a string if at all possible.

Related

Jinja - email template, date time formatting with a variable

This is driving me crazy, feels like it should be easier.
Using Jinja code for a HTML email, in a drag and drop editor - so no access to the <head>!
I have a date I’ve set as a variable the date format is YYYY-MM-DD HH:MM:SS
I want to change the format using datetimeformat function, it works fine as {{ today()|datetimeformat("%y-%m-%d") }} - but I'll be buggered if I can exchange today() with my variable.
{% set bonusBeforeDate = linkedData.accessCodes[userAttribute['ReferralSource']]['promotion']['rules']['member_joined_date']['before'] %}
And then
{{ bonusBeforeDate|datetimeformat("%y-%m-%d") }}
OK, someone very kind has helped me out with this one, so I'll share it here in the hope it saves anyone else the headache later.
The reason it is not working is because datetimeformat requires datetime object, while yours is a string. The today() function returns datetime object, so it works directly. You will have to perform some transformations to get this working. The following sequence needs to be followed:
Convert your string to another suitable string to represent datetime object. Not all date looking strings can be converted to datetime object, they need to follow a specific format.
Now convert the new string to a datetime object (strtotime)
Apply any datetime formatting to the date time object (datetimeformat)
In practical terms with your example:
Step 1:
{% set myDate='2020-12-31 12:59:00' %}
{% set myDateFormatted = myDate|split(' ',2) %}
{% set myDateFinalFormat = myDateFormatted[0]+'T'+myDateFormatted[1]+'Z' %}
The value of myDateFinalFormat at this point should be 2020-12-31T12:59:00Z which is the exact string format we are interested in.
Steps 2 and 3:
{{ myDateFinalFormat|strtotime("yyyy-MM-dd'T'HH:mm:ssXXX")|datetimeformat("%y-%m-%d") }}
This will output: 20-12-31

Datetime in django with template filter will show different value

I'm using Django template filters to format a datetime instance, but it looks like its value differs from raw date in the datebase.
I used datetime.now() in Python to create the instance.
{{ modeltest.date }}
will show
"Jan. 3, 2019, 5:27 a.m."
on the page, but
{{ modeltest.date | date:"Y-m-d H:m:s" }}
displays
"2019-01-03 05:01:19"
Note the difference of the minutes displayed (5:27 vs 05:01)
I'm getting a little confused here.
Does anyone know this?
You mixed up the date filters. You used the month twice (lowercase m) instead of using minutes (lowercase i).
You are seeing "2019-01-03 05:01:19" (with the minutes as 01 instead of 27) because it actually show the month (January is the first month, so 01).
You can change this
date:"Y-m-d H:m:s"
to
date:"Y-m-d H:i:s"

Creating a date filter in jinja2

I'm trying to work out the age of a record in my jinja2 with a filter. I created a simple filter in the following way. The date is stored in a mongodb field and its original form should be of the format of the python datetime object. Here is an example of the record:
"date_update": {
"$date": "2016-02-29T11:13:41.730Z"
},
app.jinja_env.filters['record'] = lambda u: record(u)
def record(date_obj):
print(date_obj)
print(type(date_obj))
return (datetime.datetime.today() - date_obj).days
I use the filter in the following way:
{{ myrec.date_update|record }}
If I look at the output, I see the following:
class 'jinja2.runtime.Undefined'
So my question is, how best should I deal with the dates in jinja2 in the correct format.
This looks like an unknown variable name within your template. From all you've posted so far, it is not clear whether you pass a variable myrec to the template renderer in the first place. So for better help, please post a minimal, self-contained example that exhibits the error.

Django template datetime.weekday name

Is there a way to display the weekday of a datetime object in a template as the actual name of the weekday? Basically I want it to print Friday instead of 5.
See the documentation for the built-in date filter. From there you'll see you need to use:
l Day of the week, textual, long. 'Friday'
For clarity's sake, the template tag format character "l" (lower-case "L") can be used in the Django template like so:
{{ object.some_date_field | date:"l" }}
Django 1.8.2
You can also use:
import datetime
today = datetime.datetime.today()
print(today.strftime('%A'))

django autoconverting datetime property

my datetime property is saving in mysql in this format 2011-03-17 00:00:00 but after fetchind the data with filter function it is giving March 17,2011 midnight but i have not say to do any this type of task. My question is how can i insist django to stic to show same value what is saved in MYSQL.
you'll want to use the datetime format, django's DateTimeField[1] really is a wrapper for datetime.datetime.
in the templates you can use the date[2] filter to apply the format you want for example:
{{ item.date|date:"Y-m-d H:i:s" }}
This should print out 2011-03-17 00:00:00 in the template. In views use datetimes.strftime[3]
[1] http://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield
[2] http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#date
[3] http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
I have a feeling your database schema knows this is a date, right? In that case it's not being stored in the format you describe, but as some representation such as seconds since the era.
This means that when you retreave it your code has to do something with it to make it look right. If you don't tell it how to look it'll default to the format you see, but if you use strftime in your python code and a filter in your templates you can make it look however you like, including the original format how you saw it.
Of course the easy way out is to store it in the db as text...

Categories

Resources