Python time Common Method summary

Source: Internet
Author: User
Tags current time datetime time zones julian day month name time interval timedelta in python

Let's first import a module that must be used

The code is as follows Copy Code
>>> Import Time

Set a time format, which is used in the following

The code is as follows Copy Code
>>>isotimeformat= '%y-%m-%d%x '

Look at the current time, similar to many other languages this is from epoch (January 1, 1970 00:00:00) to the current number of seconds.

The code is as follows Copy Code
>>> Time.time ()
1180759620.859

The above can not understand, change the format to see

The code is as follows Copy Code
>>> Time.localtime ()
(2007, 6, 2, 12, 47, 7, 5, 153, 0)

LocalTime returns the tuple format, there is a function similar to it called Gmtime (), the difference between 2 functions is time zone, Gmtime () returns the value of the 0 time zone, LocalTime returns the value of the current time zone.

The code is as follows Copy Code
>>> time.strftime (Isotimeformat, Time.localtime ())
' 2007-06-02 12:54:29′

With our time format defined, use Strftime to make a transition to time, if you take the current time, time.localtime () can not.

The code is as follows Copy Code
>>> time.strftime (Isotimeformat, Time.localtime (Time.time ()))
' 2007-06-02 12:54:31′
>>> time.strftime (Isotimeformat, Time.gmtime (Time.time ()))
' 2007-06-02 04:55:02′

The above shows the difference between Gmtime and localtime.
View time zones with
>>> Time.timezone
-28800
The above value is a second value, is the current time zone and 0 time zone difference description, -28800=-8*3600, that is, East eight area.

You can try the following way to get the time stamp of the current time:
Import time
Print Time.time ()
The result of the output is:
1279578704.6725271

But this is a series of numbers that are not the result we want, and we can use the time module's format to handle:
Time.localtime (Time.time ())
Using the Time.localtime () method, the effect is to format the time that the timestamp is local.
The result of the output is:
Time.struct_time (tm_year=2010, tm_mon=7, tm_mday=19, tm_hour=22, tm_min=33, tm_sec=39, tm_wday=0, tm_yday=200, tm_ isdst=0)

Now it looks like it's a more hopeful format for the time we want.
Time.strftime ('%y-%m-%d ', Time.localtime (Time.time ()))

Finally, using the Time.strftime () method to format just a bunch of information into what we want, now the result is:
2010-07-19


Post a few simple functions

The code is as follows Copy Code

def isostring2time (s):
'''
Convert a ISO format time to second
from:2006-04-12 16:46:40 to:23123123
To convert a time into seconds
'''
Return Time.strptime (S, Isotimeformat)
def time2isostring (s):
'''
Convert second to a ISO format time
from:23123123 to:2006-04-12 16:46:40
Converts a given second to a defined format
'''
Return Time.strftime (Isotimeformat, Time.localtime (float (s))
def dateplustime (d, T):
'''
D=2006-04-12 16:46:40
T=2 hours
return 2006-04-12 18:46:40
Calculate how many seconds a date differs, Time2sec is another function that can be processed, 3 days, 13 minutes, 10 hours, etc. strings, back to write this, you need to combine regular expressions.
'''
Return time2isostring (Time.mktime (Isostring2time (d)) +time2sec (t))
def datemindate (D1, D2):
'''
Minus to ISO format date,return seconds
Calculate how many seconds to 2 time difference
'''
D1=isostring2time (D1)
D2=isostring2time (D2)
return Time.mktime (D1)-time.mktime (D2)


Time module provides functions for various operating times

Description: There are generally two ways to represent time:
The first is the time stamp (as opposed to the offset in seconds in 1970.1.1 00:00:00), the timestamp is unique
The second type is represented as an array (struct_time), with a total of nine elements, Each indicates that the struct_time of the same timestamp differs depending on the time zone

  code is as follows copy code

Year (four digits, e.g. 1998)
Month (1-12)
Day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
Weekday (0-6 , Monday is 0)
"Julian Day", 1-366)
DST (Daylight Savings Time) flag ( -1, 0 or 1) whether it is daylight saving time
if the DST flag is 0, the time was given in the regular time zone;
If it is 1, the time is given in the DST time zone;
If it is-1, mktime () should guess based on the date and time.

Second, Function introduction
1.asctime ()
Asctime ([tuple])-> string
Converts a struct_time (default is Time) to a string
Convert a time tuple to a string, e.g. ' Sat June 06 16:26:11 1998′.
When the time tuple isn't present, current time as returned by LocalTime ()
is used.

2.clock ()
Clock ()-> floating point number
This function has two functions,
At the first call, it returns the actual time the program is running;
After the second call, returns the time interval from the first call to this call

Example:

The code is as follows Copy Code
View Plaincopy to Clipboardprint?
Import time
if __name__ = = ' __main__ ':
Time.sleep (1)
Print "clock1:%s"% Time.clock ()
Time.sleep (1)
Print "clock2:%s"% Time.clock ()
Time.sleep (1)
Print "clock3:%s"% time.clock () output:
clock1:3.35238137808e-006
clock2:1.00004944763
clock3:2.00012040636

The first clock output is the program run time
The second to third clock output is the time interval with the first clock

3.sleep (...)
Sleep (seconds)
The thread defers the specified time run, tested in seconds, but in the Help document, the following sentence is not understood
"The argument May is a floating point number for subsecond precision."

4.ctime (...)

The code is as follows Copy Code
CTime (seconds)-> string

Converts a timestamp (the default current time) into a time string
For example:

Time.ctime () output is: ' Sat Mar 28 22:24:24 2009′

5.gmtime (...)

The code is as follows Copy Code
Gmtime ([seconds])-> (Tm_year, Tm_mon, Tm_day, Tm_hour, Tm_min,tm_sec, Tm_wday, Tm_yday, TM_ISDST)

Converts a timestamp to the struct_time of a UTC time zone (0 o'clock) and, if the seconds parameter is not entered, the current time as the conversion standard

6.localtime (...)

The code is as follows Copy Code
LocalTime ([seconds])-> (TM_YEAR,TM_MON,TM_DAY,TM_HOUR,TM_MIN,TM_SEC,TM_WDAY,TM_YDAY,TM_ISDST)

Converts a timestamp to the struct_time of a current time zone, and if the seconds parameter is not entered, the current period is the conversion standard

7.mktime (...)

The code is as follows Copy Code
Mktime (tuple)-> floating point number

Converts a struct_time to a timestamp

8.strftime (...)
Strftime (format[, tuple])-> string
Converts the specified struct_time (the default current time) to the specified formatted string output
Time date format symbol in Python:
%y Two-digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m Month (01-12)
Day of%d months (0-31)
%H 24-hour hours (0-23)
%I 12 Hours of hours (01-12)
%m minutes (00=59)
%s seconds (00-59)

%a Local Simplified Week name
%A Local Full week name
%b a locally simplified month name
%B Local Full month name
%c Local corresponding date representation and time representation
%j Day of the Year (001-366)
%p the equivalent of a local a.m. or p.m.
%u number of weeks in a year (00-53) Sunday is the beginning of the week
%w Week (0-6), Sunday for the beginning of the week
%w number of weeks in a year (00-53) Monday is the beginning of the week
%x Local corresponding date representation
%x Local corresponding time representation
%Z the name of the current time zone
%%% per se

9.strptime (...)
Strptime (string, format)-> Struct_time
Converts a time string to an array of times based on a specified format character
For example:
2009-03-20 11:45:39 The corresponding format string is:%y-%m-%d%h:%m:%s
Sat 28 22:24:24 2009 The corresponding format string is:%a%b%d%h:%m:%s%Y

10.time (...)
Time ()-> floating point number
Returns the time stamp for the current time

Python, time subtraction, time calculation, time format, time extraction Summary


Give a complete

The code is as follows Copy Code

#!/usr/bin/python
#coding: Utf-8
Import datetime
Import time

format= "%y-%m-%d%h:%m:%s"
T1=time.strptime ("2008-01-31 00:11:23", format)
T2=datetime.datetime (T1[0],t1[1],t1[2],t1[3],t1[4],t1[5],t1[6])
T3=t2-datetime.timedelta (minutes=30)
T3=str (T3)

B1=t3[0:4]
B2=t3[5:7]
B3=T3[8:10]
B4=T3[11:13]
B5=T3[14:16]
B6=t3[-2:]

Print B1
Print B2
Print B3
Print B4
Print B5
Print B6

Another method of time formatting xiaoyu9805119 provides

The code is as follows Copy Code
A= "2009-02-15 21:00:08"
Import re
S=re.split ("d*", a)
Print S

Another time plus minus method 3227049 provides

  code is as follows copy code

Import Datetime,time

format= "%y-%m-%d%h:%m:%s"

Result=datetime.datetime (*time.strptime ("2008-01-31 00:11:23 ", format) [: 6])-datetime.timedelta (minutes=30)

Print result.strftime (format)

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.