A tutorial on using dates and times in the Python flask framework

Source: Internet
Author: User
Tags datetime time zones iso 8601 local time min requires time and date

This article mainly introduces the use of date and time tutorials in the Python flask framework, including some processing of transitions between time zones, and the need for friends can refer to the following

Problem with time stamp

One of the long neglected problems with our microblog applications is the display of daytime and date.

Until now, we have used Python's own way of rendering the time object in our user and post objects, but this is not a good solution.

Consider such an example. I am writing this article, this is December 31 3:54. My time zone is PST (or you are more accustomed to: UTC-8). Running in the Python interpreter, I get the following output:


1 2 3 4 5 6 7 >>> from datetime import datetime >>> today = DateTime.Now () >>> print now 2012-12-31 15:54:42.91 5204 >>> now = Datetime.utcnow () >>> print now 2012-12-31 23:55:13.635874

Where I am, the Now () method returns the correct time, but the time returned by the Today () call is the UTC unit.

So, which is better to use?

If we use now (), the timestamp in all databases will be the same as the local time the server is running, which will create some problems.

For example, if one day we need to place the server somewhere else (not in a time zone), the time in the database needs to be updated to match the new location before restarting the server.

There will be more important issues. Users in different time zones will find it difficult to know when to send a message, and if the user sees a PST time zone, it is difficult to know when the message was sent, which requires the user to adjust accordingly.

Obviously this is not a good choice, which is why we use the UTC time zone to save the timestamp when we create the database.

The problem with the mobile server was resolved when the standardized timestamp was UTC. But he couldn't solve the second problem, with data and time being presented to users in different parts of the world using UTC.

Suppose a user sends an e-mail message in the PST time Zone 3 o'clock in the afternoon, which immediately appears in front of him, 11:00pm, or more specifically (23:00).

The purpose of my writing this article is to make our users no longer confused by the display of data and time.

Use a specific time stamp

The usual solution is for each user to convert from UTC to local time. This requires us to change dynamically so that the UTC of the database is aligned with it.

But how do we know where the user is?

Many sites have a settings page that sets their time zone. This requires us to add a new page, and provide a Drop-down box on the form to allow the user to select the time zone, the first time the user login needs to set the time zone, and as part of the registration.

This is a normal workaround, but this is a bit cumbersome for users, who need to enter a message that they have configured in the operating system. So if we can grab the time zone set on the user's computer, the problem will become more efficient.

For security reasons, browsers do not allow us to access the user's operating system for information. Even if it does, we need to know where to get the time zone in Windows,linux,mac,ios,android, which does not include other non-mainstream operating systems.

Gets the user's time zone in the browser, and then through the standard JavaScript API. In the Web 2.0 world, users allow JavaScript to execute (few sites do not use JavaScript), so it is possible to get user time zones via JavaScript.

We use JavaScript to configure the available time zones in two ways:

Old-fashioned way: When a user logs on to the server for the first time, let the browser send time zone information to us in some way. This can be invoked via Ajax or, more simply, through the meta-refresh tag. Once the server knows the time zone information, it can save it in the user session, and then adjust the time display for all pages.

The new approach: do not change anything on the server side, but still send a UTC timestamp to the client browser. The work of converting UTC to local time is performed through JavaScript on the client.

Both methods are valid, but the second one is more advantageous. The browser can perform the best time conversion according to the local configuration of the system. Like the morning/afternoon vs 24-hour system, day/month/year vs month/day/year and other cultural formats that browsers can access, the server is not necessarily.

If that's not enough, there's a bigger advantage to the new pie, and someone else has done it for us (Moment.js is coming)!

Moment.js Introduction

Moment.js is a small, free, open source JavaScript library that promotes dates and events to another level. It provides all the time and date formats imaginable, and here are some.

To use Moment.js in our application, we need to write a lost JavaScript code in our template file. Let's start by using ISO 8601 time to create a moment object. For example: Create a Moment object from the UTC time of the python example above, like this:


1 Moment ("2012-12-31t23:55:13 Z")

Once an object is created, it can be transformed into a string of various format types. For example, the time to convert a gray-long time display to the Local system:


1 Moment ("2012-12-31t23:55:13 Z"). Format (' llll ');

The following is the transition time display:


1 Tuesday, January 1 2013 7:55 AM

Here are a few more examples of converting the same timestamp into different formats:

This class library supports the conversion options more than that. In addition to format (), it provides Fromnow () and calendar () For more friendly timestamp conversions:

Note that in all of the above examples, the server converts the same UTC time, and your own local browser converts different times.

Finally, we'll make up for some of the missing JavaScript tips, and it's obvious in the page that the code actually returned the string type by moment. The simplest way to accomplish this is to use the Document.Write method of javascript:


1 2 3 <script> document.write (Moment ("2012-12-31t23:55:13 Z"). Format (' llll '); </script>

Using JavaScript's document.write is a simple and straightforward way to generate part of the HTML code, but note that there are some limitations to this approach. The most needed point is that the Document.Write method can only be used when the document is loaded, and when the document is loaded, it cannot modify the document. The result of this limitation is that the solution will fail when the data is loaded through Ajax.

Integrated Moment.js

Here we need to do a little something to add moment.js to our microblog.

First, we need to download moment.min.js this library into the/app/static/js folder so that it can serve as a static file for the client.

Then we add the reference to this library (moment.min.js) in our template file (fileapp/templates/base.html):


1 <script src= "/static/js/moment.min.js" ></script>

Now we can add in the template file

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.