Common operations for TIME modules and datetime modules in Python and conversions between several common temporal formats

Source: Internet
Author: User

Some of the most common and common time formats

1, timestamp (timestamp), the timestamp represents the offset that is calculated in seconds, starting January 1, 1970 00:00:00.

2, Time tuple (struct_time), a total of nine element groups.

3. Format time, formatted as a fixed or custom format, to increase readability.

#!/usr/bin/env python# -*- coding:utf-8 -*-import time# timestamp format, gets the current time by default   1500029143.7640195timestamp = time.time () print ("Get current timestamp:", timestamp) #获取元组 (struct_time) Form, The default gets the current time Struct_time_utc8= time.localtime () print ("Get current East 8 zone (China) Time:", Struct_time_utc8) struct_time_utc=  Time.gmtime () print ("Get Current World Time:", STRUCT_TIME_UTC) "Note: UTC (Coordinated universal time, World coordination) is Greenwich Astronomical time, world standard Time. In China for Utc+8. DST (Daylight saving time) is the time-saving "#获取格式化后的时间, which is formatted as a string in%y-%m-%d %h:%m:%s format format_time =  time.strftime ("%y-%m-%d %h:%m:%s", Time.localtime ()) print ("Time after formatting in the specified format:", Format_time) #   fri jul 14 18:45:43 2017 (%a %b %d %h:%m:%s %y) format # converts time in timestamp format to%a % B %d %h:%m:%s %y format, the default is to format the current time Style_time1 = time.ctime () print ("Convert timestamp to%a %b  %d %h:%m:%s %y format: ", style_time1) #将元组 (struct_time) Form of time converted to%a %b %d %h:%m:%s  %y format, the default is to also format the current time of StYle_time2 = time.asctime () print ("Convert similar to tuple (struct_time) to%a %b %d %h:%m:%s %y format:", style_time2) ' Run result gets current timestamp:  1500029371.4988112 gets current time in East 8 (China):  time.struct_time (Tm_year=2017, tm _mon=7, tm_mday=14, tm_hour=18, tm_min=49, tm_sec=31, tm_wday=4, tm_yday=195,  tm_isdst=0) Gets the current world time:  time.struct_time (tm_year=2017, tm_mon=7, tm_mday=14, tm_hour= 10, tm_min=49, tm_sec=31, tm_wday=4, tm_yday=195, tm_isdst=0) The time after formatting in the specified format:  2017-07-14 18:49:31 convert timestamps to%a %b %d %h:%m:%s %y format: fri jul 14  18:49:31 2017 convert similar tuples (struct_time) to%a %b %d %h:%m:%s %y format:  fri jul 14  18:49:31 2017 ""

Some basic concepts

1. Timestamp (timestamp) in the form of: Typically, a timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. The function that returns the Timestamp method mainly has time (), clock (), etc., the default is to return the timestamp of the current time.

2. Tuple (struct_time) in the form of: Struct_time tuples have a total of 9 elements. The functions that return struct_time are mainly gmtime (), localtime (), Strptime (), and the default is the tuple (struct_time) Form that returns the current time, However, other time periods or other forms of time format can also be converted to a tuple (struct_time) Form.

Struct_time Tuple 9 Elements Detailed description:

"0 tm_year (years) such as 20111 Tm_mon (month) 1-122 Tm_mday (day) 1-313 Tm_hour (time) 0-234 tm_min (min) 0-595 tm_se C (SEC) 0-616 Tm_wday (weekday) 0-6 (0 for Sunday) 7 Tm_yday (Day of the year) 1-3668 TM_ISDST (Daylight saving time) by default-1 "

Conversion of several time formats

#!/usr/bin/env python# -*- coding:utf-8 -*-import time# converts a timestamp into a tuple (struct_ Time format: Tuple_struct = time.localtime (1499703018.0) print ("Convert a timestamp to a time format like a tuple:", tuple_struct )     #将一个时间戳转化为一个类似元组形式的时间格式:  time.struct_time (tm_year=1973, tm_mon=11, tm_mday= 30, tm_hour=5, tm_min=33, tm_sec=9, tm_wday=4, tm_yday=334, tm_isdst=0) # Converts a time format in the form of a tuple (struct_time) to a timestamp:t =  (2017, 7, 11, 0, 10, 18, 1, 192 ,  0) Timestamp1 = time.mktime (Time.struct_time (t)) print ("Converts a time format similar to a tuple to a timestamp:", TIMESTAMP1) # Converts a time format in the form of a tuple (struct_time) to a specified format such as:%y-%m-%d %h:%m:%sformat_time1 = time.strftime ("%y-%m-%d % h:%m:%s ", T)    #2017 -07-11 00:10:18print (" Converts a time format similar to element form to a specified format such as:%y-%m-%d %h:%m:%s: ", Format_ TIME1) #将格式化后的时间转化成元组 (struct_time) Form of time format tuple_struct2 = time.strptime ("2017-07-11 00:10:18", "% y-%m-%d %h:%m:%s ") print (" will formatAfter the time conversion into a tuple form of the time format: ", Tuple_struct2) ' Run the result of a timestamp into a similar tuple form of time format:  time.struct_time (tm_year=2017, tm_ mon=7, tm_mday=11, tm_hour=0, tm_min=10, tm_sec=18, tm_wday=1, tm_yday=192,  tm_isdst=0) converts a time format similar to a tuple into a timestamp:  1499703018.0 converts a time format like an element into a specified format such as:%y-%m-%d %h:%m:%s:  2017-07-11 00:10:18 converts the formatted time into a tuple format:  time.struct_time (tm_year=2017, tm_mon=7, tm_mday= 11, tm_hour=0, tm_min=10, tm_sec=18, tm_wday=1, tm_yday=192, tm_isdst=-1) ""

To facilitate the understanding and memory of the conversion of these common time formats, see the following diagram:

650) this.width=650; "Src=" https://s2.51cto.com/wyfs02/M02/9B/EC/wKiom1loqGmxOdXAAACPxszZbcQ185.png-wh_500x0-wm_ 3-wmp_4-s_2557178467.png "title=" Drawing 1.png "alt=" Wkiom1loqgmxodxaaacpxszzbcq185.png-wh_50 "/>

Reference Help information when formatting time

Reference Help information when formatting time:%a   local (locale) simplified week name     %A   Local full week name      %b   Local Simplified month name     %B   Local full month name     %c    local corresponding date and time representation     %d   Day of the one month (01 - 31)    %h    hours of the day (24-hour, 00 - 23)     %I   hours (12-hour, 01 -  12)     %j   Day of the Year (001 - 366)   %m   Month (01  - 12)  %M   minutes (00 - 59)     %p   corresponding characters for local AM or PM     %S   seconds (01 - 61)   %U   number of weeks in a year. (00 - 53 Sunday is the beginning of one weeks.) All days before the first Sunday are placed in the No. 0 week. The day of the    %w   one week (0 - 6,0 is Sunday)    three%w   and%u are basically the same, the difference is% W takes Monday as the beginning of one weeks.  %x   Local corresponding date   %X   local time   %y   year of the Century (00 - 99)     %Y   full year    %Z   time zone name (if not present as null character)      %%   '% ' character '

######################################################

The DateTime module encapsulates the time module, providing more classes such as date, time, DateTime, Timedelta, and so on.

Common usage examples of 1.datetim.data

#!/usr/bin/env python# -*- coding:utf-8 -*-import datetime#  Gets a Date object d =  datetime.date (2017,7,14)     #参数年, month, day #data can represent the maximum date d_max = d.maxprint (" Data can represent the maximum date: ", D_max) #data能表示的最小日期d_min  = d.minprint (" Data can represent the maximum date: ", D.Min) #获取当前日期d_today  =  d.today () print ("Get Current date:", D.today ()) #获取年, month, day year = d.yearmonth = d.monthday =  d.dayprint ("Get year%s, month%s, day%s"%  (year,month,day)) #根据给定的时间戳返回对应的日期d_date  = d.fromtimestamp ( 12312432432) Print ("returns the corresponding date based on the given timestamp:", d_date) #返回weekday, if Monday returns 0, Tuesday returns 1, and so on, 2017-7-14 is Friday d_weekday =  d.weekday () Print ("Return weekday to:", D_weekday) #返回格式化为 (YYYY-MM-DD) string D_format = d.isoformat () print ( "Returns the formatted (YYYY-MM-DD) string:", D_format) #返回格式化的日期字符串类似time模块的strftimed_strftime  = d.strftime ("%y-%m-%d  %h:%m:%s ") Print (" formatted string: ", D_strftime) #返回时间的元组 (struct_time) Form d_tuple = d.timetuple () print (" Returns the time of the tuple (struct_time) Form: ", D_tuple) ' Running the result datThe maximum date A can represent:  9999-12-31data The maximum date that can be represented:  0001-01-01 gets the current date:  2017-07-14 Gets the year 2017, month 7, day 14 returns the corresponding date based on the given timestamp:  2360-03-02 returns weekday as:  4 returns the formatted (YYYY-MM-DD) string:  2017-07-14 formatted string: 2017-07-14  00:00:00 returns the time of the tuple (struct_time) Form:  time.struct_time (tm_year=2017, tm_mon=7, tm_mday=14, tm_ Hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=-1) ""

Common usage examples of 2.datetime.time

#!/usr/bin/env python#-*-coding:utf-8-*-import Datetimedt = Datetime.time (17,30,00) #参数时, minutes, seconds #time can represent the maximum time Dt_max = dt. Maxprint ("Maximum time that can be represented:", dt_max) #time能表示的最小时间dt_min = Dt.minprint ("The minimum time that can be represented:", dt_min) #获取时, minutes, seconds, subtle hour = Dt.hourminute = Dt.minutesecond = Dt.secondmicrosecond = Dt.microsecondprint ("Get%s, Min%s, sec%s, subtle%s"% (Hour,minute,second,microsecond) ) #返回时间的格式化字符串 (HH:MM:SS) Dt_format = Dt.isoformat () print ("Return time formatted String (HH:MM:SS):", Dt_format) #格式化, Strftimedt_strftime = Dt.strftime ("%h:%m:%s") Print ("Formatted:", "Dt_strftime"), similar to the time module, can represent the maximum number of times that a run result could be: 23:59:59.999999 minimum time: 00:00:00 gets 17, minute 30, second 0, subtle 0 format string to return time (HH:MM:SS): 17:30:00 format: 17:30:00 "

Common usage examples of 3.datetime.datetime

#!/usr/bin/env python# -*- coding:utf-8 -*-import datetime# gets the current local time d_today =  datetime.datetime.today () print ("Get current local time:", D_today) #获得当前时间, if the time zone parameter TZ is provided, gets the time of the specified time zone according to the time zone parameter d_now =  datetime.datetime.now () print ("Get Current Time:", D_now) #获取当前的世界标准时间 (i.e. Greenwich Astronomical time) d_utc =  Datetime.datetime.utcnow () print ("Get the current world standard Time (i.e. Greenwich Astronomical time):", D_UTC) #将时间戳转化成格式化的字符串, you can convert the time zone parameter tz to the formatted time of the specified time zone D_ Fromtimestamp = datetime.datetime.fromtimestamp (123214324) print ("Convert timestamp to formatted string:", D_fromtimestamp) # Formats the D_utcfromtimestam = datetime.datetime.utcfromtimestamp (123214324) print (") according to the timestamp in UTC standard Time zone time. Converts a timestamp to a formatted string in UTC's Standard timezone time: ", D_utcfromtimestam)" Note that by comparing the results of the above output, we will find that the time stamp obtained by Fromtimestamp and Utcfromtimestamp conversion is exactly the same as 8h "################# #dd  =  Datetime.datetime (2017,7,14,17,30,00) #将指定的时间转化成格式化的字符串, similar to time strftimedd_strftime = dd.strftime ("% y-%m-%d %h:%m:%s ") print (" Format specified time ", dd_strftime) #返回weekday if Monday returns 0, Tuesday returns 1, and so on, 2017-7-14 is Friday dd_ weekday =&Nbsp;dd.weekday () Print ("Return weekday to:", Dd_weekday) #获得元组 (struct_time) Form of time format dd_timetuple = dd.timetuple () print ("Get the time format in tuple (Struct_time):", Dd_timetuple) #dd_utctimetuple  = dd.utctimetuple ()   # Get # in UTC standard Returns a string formatted as%y-%m-%d %h:%m:%s format Dd_isoformat = dd.isoformat () print ("Returns a formatted%y-%m-%d  %h:%m:%s format string: ", Dd_isoformat) ' run result gets current local time:  2017-07-14 18:57:59.309859 get current time:  2017-07-14 18:57:59.309858 Gets the current world standard Time (Greenwich Astronomical Time):  2017-07-14 10:57:59.309858 converts a timestamp into a formatted string:  1973-11-27 10:12:04 converts the timestamp to a formatted string in UTC standard Time zone time:  1973-11-27 02:12:04 format the specified time   2017-07-14 17:30:00 returns weekday as:  4 gets the time format in the form of a tuple (struct_time):  time.struct_time (tm_year=2017,  tm_mon=7, tm_mday=14, tm_hour=17, tm_min=30, tm_sec=0, tm_wday=4, tm_yday=195,  tm_isdst=-1) returns a string formatted as%y-%m-%d %h:%m:%s:  2017-07-14t17:30:00 "

Common usage examples of 4.datetime.timedelta

#!/usr/bin/env python#-*-coding:utf-8-*-# author:yaosheng wangimport datetime# get current time Now_date = Datetime.datetime.now () print ("Get Current Time:", now_date) #获取五天后的时间five_later = Datetime.datetime.now () + Datetime.timedelta (5) print ("Get five days in time:", Five_later) #获取五天前的时间five_ago = Datetime.datetime.now ()-Datetime.timedelta (5) print ("Get five days ago:", Five_ago) # Three hours after the time Three_hour_later = Datetime.datetime.now () + Datetime.timedelta (hours=3) print ("Received three hours after:", Three_hour_ Later) ' Run result get current time: 2017-07-14 19:00:04.955596 gets five days after: 2017-07-19 19:00:04.955596 gets five days ago: 2017-07-09 19:00:04.955596 received three hours: 2017-07-14 22:00:04.955596 "


Common operations for TIME modules and datetime modules in Python and conversions between several common temporal formats

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.