I am sending the following datetime timezone aware object to django template
current_time = timezone.now()
In my template i am showing it using
{{ current_time }}
it displays as:
Feb. 10, 2021, 3:25 a.m
I want it to display as
Feb. 10, 2021, 3:25 a.m UTC
I dont see which timezone the time is. So i want to be more clear by adding the timezone.
how can i do this in django template
try this
{{ current_time |date:"b d Y f a T" }}
b:Month, textual, 3 letters, lowercase. 'jan'
d:Day of the month, 2 digits with leading zeros. '01' to '31' Y:Year,
4 digits. '1999'
f:Time, in 12-hour hours and minutes, with minutes left off if
they’re zero. Proprietary extension.
a:'a.m.' or 'p.m.' (Note that this is slightly different than PHP’s
output, because this includes periods to match Associated Press
style.) 'a.m.'
T:Time zone of this machine. 'EST', 'MDT'
you can see more about date template on here:https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#date
Related
I have a question about python, I am saving the current months and year using strftime() in the format of %y %m so the value will display like '17 01'. This is how I get the year and month
from time import gmtime, strftime
strftime("%y %m" ,gmtime())
print strftime()
I am currently using SQLite and I wish to call a function to check in my DB means that before the unique ID was generated and display. I wish to know that whether there is changes in month ?? if yes, the auto increment need to start from 0, if no the auto increment will just continue
Both of the value will be display as a ID and will be save as int to the database, and after the year and month have a auto increment integer (the string will look like these
(y)(m)(auto increment)
17 10 001
how to write a code when there is changes on %y or %m , I will trigger a command and run
db.engine.execute("ALTER TALBE myDB.myTable AUTO_INCREMENT=0;")
I'd like to specify 12 PM on a particular date in the central timezone and adjust for daylight savings time (CDT). I'd then like to convert this to a POSIX timestamp.
The first thing I reached for is:
d = datetime.datetime(2017, 6, 27, 12, tzinfo=???)
But I don't have a concrete CDT class. pytz does however:
z = pytz.timezone('EST5EDT')
d = datetime.datetime(2017, 6, 27, 12, tzinfo=z)
But this does not work (pytz documentation says as much but I don't understand why the constructor cannot use the timezone information). If I use November (fall back) or June (spring forward) I get still get 12:00:00-05:00 as the time portion.
Even if this did work the method to convert to a POSIX timestamp assumes a naive datetime:
posix = time.mktime(d.timetuple())
This timestamp represents 12PM in my local time zone.
Then there is normalize() with code and examples that I find very difficult to follow:
au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
I also tried to subtract my aware time from an epoch defined at January 1, 1970 but that doesn't work unless the datetime gets the UTC offset correct (see my second point above).
Can anyone help me with a mental model of how this stuff works in general and a solution to this problem in particular?
This solution seems to work:
import pytz
import datetime
# Naive datetime (no timezone).
d = datetime.datetime(2017, 11, 27, 12)
cdt = pytz.timezone('US/Central')
# Give it a central time zone context.
d = cdt.localize(d)
# Determine the time in UTC.
d = d.astimezone(pytz.utc)
# Create a naive POSIX epoch.
epoch = datetime.datetime(1970, 1, 1)
# Give it context in the UTC time zone.
epoch = pytz.utc.localize(epoch)
# Number of seconds have elapsed since the epoch.
print (d - epoch).total_seconds()
We have a Rails 4 application .
What is the best way to schedule whenever task in rails in midnight usa with daylight saving ?
We need to send email at 11.58pm in night of a day's report .
We are using tzinfo gem
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse('11:58pm')).strftime('%H:%M%p')
is not sending email at the time .
This works around the timezone issue, server is at UTC and users in another time zone (with daylight saving time). define a local action and use in cronjob.
schedule.rb
require "tzinfo"
def local(time)
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse(time))
end
every :sunday, at: local("11:58 pm") do
#your email sending task
end
hope it will help you.
Rehan's answer was SO great! In my use case I ran into an issue where the time zone conversion also changed the day of the week the task would be scheduled for.
Perhaps there is an easier way but here is what I did.
The timezone conversion we needed would only advance the weekday.
If your use case requires the weekday to be retreated then you will need to edit this, but it should be an easy fix.
def local(time, est_weekday = nil)
days = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday]
local_time = Time.parse(time)
utc_time = TZInfo::Timezone.get('America/New_York').local_to_utc(local_time)
utc_time_formatted = utc_time.strftime("%I:%M %p")
if est_weekday && days.include?(est_weekday.downcase.to_sym)
#extract intended wday for ruby datetime and assign
weekday_index = days.index(est_weekday.downcase.to_sym)
#get placeholder wday from desired EST day/time
temp_est_weekday_index = local_time.wday
#get placeholder wday from adjusted UTC day/time
temp_utc_weekday_index = utc_time.wday
#has the conversion to UTC advanced the wday?
weekday_advances = temp_utc_weekday_index != temp_est_weekday_index
#adjust wday index if timezone conversion has advanced weekday
weekday_index += 1 if weekday_advances
weekday = days[weekday_index]
return {time: utc_time_formatted, day: weekday || nil }
else
return utc_time_formatted
end
end
Is there a way (Using Django filters or any other language) to find and slice certain parts of a dynamically generated string? I have tried the slice method and the truncate method
{{variable|slice:"130:-60"}} or
{{variable|truncatechars:255 }}
but neither of those methods work exactly right..... I am working on weather alerts (provided by the National Weather Service) and each alert comes with a unique ID on the front and (sometimes) on the back too.
The unique ID #'s and length vary between 60 and 130 characters and the ID at the end is longitude and latitude but it's only included about 1/2 the time.
So I am looking for / working on code to "sniff out" and remove the unique ID's and to only provide the text for the user to see.
What is the proper method to do this?
Here is an example of an alert:
INC077-437-75584393-/09584738.EGY/W.0027//KT.0215401321/ 1100 AM CDT WED MAY13 2015 THE FLOODING WILL CONTINUE FOR THE MISSISSIPPI RIVER NEAR ORLANDO FLORIDA. FROM THIS EVENING TO THE END OF TIME AT 600 AM WEDNESDAY THE STAGE WAS 30.5 FEET. FLOOD STAGE IS 30.6 FEET IMPACT BY TONIGHT AT 1000 PM SOME WATER BEGINS TO FILL SOME DITCHES. && LAT...LON 4125 5845 5458 6548 8964 5124 1234 8706 $$
and with code (where I call the variable) I want it to be:
1100 AM CDT WED MAY13 2015 THE FLOODING WILL CONTINUE FOR THE MISSISSIPPI RIVER NEAR ORLANDO FLORIDA. FROM THIS EVENING TO THE END OF TIME AT 600 AM WEDNESDAY THE STAGE WAS 30.5 FEET. FLOOD STAGE IS 30.6 FEET IMPACT BY TONIGHT AT 1000 PM SOME WATER BEGINS TO FILL SOME DITCHES.
but I can't cut or truncate because the length of every weather alert is different and each unique ID is a different # and a different length.
Any help is appreciated!
You can add a custom method to your model such as :
class Weather(models.Model):
alert = models.TextField()
#property
def get_id(self):
return self.alert.split('/')[-1]
And in your template :
<p>{{ weather.get_id }}</p>
You can also create a custom template filter :
from django import template
register = template.Library()
#register.filter(name='get_id')
def get_id(value):
return value.split('/')[-1]
And use it in your template this way :
<p>{{ weather|get_id }}</p>
Is there any way I can easily check if a string conforms to the SortableDateTimePattern ("s"), or do I need to write a regular expression?
I've got a form where users can input a copyright date (as a string), and these are the allowed formats:
Year: YYYY (eg 1997)
Year and month: YYYY-MM (eg 1997-07)
Complete date: YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
I don't have much experience of writing regular expressions so if there's an easier way of doing it I'd be very grateful!
Not thoroughly tested and hence not foolproof, but the following seems to work:
var regex:RegExp = /(?<=\s|^)\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{2})?)?\+\d{2}:\d{2})?)?)?(?=\s|$)/g;
var test:String = "23 1997 1998-07 1995-07s 1937-04-16 " +
"1970-0716 1993-07-16T19:20+01:01 1979-07-16T19:20+0100 " +
"2997-07-16T19:20:30+01:08 3997-07-16T19:20:30.45+01:00";
var result:Object
while(result = regex.exec(test))
trace(result[0]);
Traced output:
1997
1998-07
1937-04-16
1993-07-16T19:20+01:01
2997-07-16T19:20:30+01:08
3997-07-16T19:20:30.45+01:00
I am using ActionScript here, but the regex should work in most flavors. When implementing it in your language, note that the first and last / are delimiters and the last g stands for global.
I'd split the input field into many (one for year, month, day etc.).
You can use Javscript to advance from one field to the next once full (i.e. once four characters are in the year box, move focus to month) for smoother entry.
You can then validate each field independently and finally construct the complete date string.