Python time stamp and formatting time conversion implementation code, python

Source: Internet
Author: User

Python time stamp and formatting time conversion implementation code, python

In python, time-related modules mainly include time and datetime.

If you want to obtain the current system timestamp: time. time (), it is a float data type.
Obtain the current time information of the system: time. ctime () is a str-type time string, which is generally used less
To obtain the current normal date string, you can simply use str (datetime. date. today ())

There is also the mutual conversion between time and timestamp (often used ):

Conversion from date to timestamp:

import datetimeimport timet = datetime.datetime(2014,12, 6, 12, 10, 10)timestamp = time.mktime(t.timetuple())print timestamp

Time stamp to date conversion:

import datetime import timet = time.localtime(timestamp)timeStr = time.strftime('%Y-%m-%d %H:%M:%S', t)print timeStr

A common scenario is:
Push the last few days or the next few days based on one day
For example, I need to know the data for 10 days since.
In this case, we need to perform time operations. If we follow the essence, it is the conversion between the timestamp and the time.
We can get the timestamp through time to time stamp, then perform the operation on the timestamp, and then
Convert the operation result to a time string. The complete code is as follows:

import timeimport datetimet = datetime.datetime(2014, 10, 25)timestamp = time.mktime(t.timetuple())timestamp += 10 * 3600 * 24t = time.localtime(timestamp)timeStr = time.strftime('%Y-%m-%d %H:%M:%S', t)

In fact, the date module has a function that encapsulates this algorithm, and the trial is not so big code, but let's only talk about the principle, the above python time process
In fact, it should be such a process for any language.

The language tools are constantly changing. You cannot stick to a language. Instead, you can only use algorithms and ideas.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.