Python Basic Time conversion

Source: Internet
Author: User

Time Conversion

When processing time in Python, the most common is the conversion between the character form and the timestamp. Put the most basic conversions down here.

String--Timestamp
import timeimport dateutil.parser as dateparserdef str_to_timestamp(time_str)    dt = dateparser.parse(time_str)    # OR: dt = time.strptime(datetimestring, fmt)    return time.mktime(dt.timetuple())datetimestring = ‘Fri, 08 Jun 2012 22:40:26 GMT‘str_to_timestamp(datetimestring)
Timestamp, string
import timedef timestamp_to_str(ts, fmt=‘%Y-%m-%d %H:%M:%S‘):    return time.strftime(fmt, time.localtime(timestamp))timestamp = time.time()timestamp_to_str(timestamp)
Python built-in time data structure

Python internally uses a data structure similar to Namedtuple to store time. This data structure has 9 fields that can be accessed with a numeric subscript or by name.

time.struct_time(        tm_year=2014,        tm_mon=9,        tm_mday=1,        tm_hour=9,        tm_min=0,        tm_sec=0,        tm_wday=0,    # 星期几, 0~6        tm_yday=244,  # 本年的第几天, 1~366        tm_isdst=0    # 是否夏令时        )
Timestamp's Notes

Here is a small detail, the time stamp is based on the standard Time zone, and Beijing time has 8 hours of jet lag. This difference can be time.timezone obtained by obtaining the number of seconds between the standard time zone and the local time zone. For Beijing time, this value is-28800 (8*3600). So, when we take the timestamp to 86400 (the number of seconds in a day) to get the number of seconds from 0 o'clock, there will be a difference of 8 hours. Other words

time.mktime(dateparser.parse(‘2014-09-01 09:00:00‘).timetuple()) % 86400

Will output 3600, just 8 hours from 9 o'clock in the morning.

Python Basic Time conversion

Related Article

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.