Home > Backend Development > Python Tutorial > Detailed introduction to Python timing related operations

Detailed introduction to Python timing related operations

黄舟
Release: 2017-05-28 11:07:22
Original
1500 people have browsed it

This article mainly introduces Python timing related operations, involving time, datetime module usage skills, including Timestamp, time difference, date format and other operation methods, friends in need can refer to the following

The examples in this article describe Python timing related operations. Share it with everyone for your reference, the details are as follows:

Content directory:

1. Timestamp
2. Current time
3. Time difference
4. Time and date formatting symbols in python
5. Example

1. Timestamp

The timestamp is since 1970 The total number of seconds from January 1st (08:00:00 GMT) to the current time. It is also called Unix Timestamp, which can be seen everywhere in the world of Unix and C; the common form is a floating point number, with milliseconds after the decimal point. The subtraction of two timestamps is the time interval (unit: seconds).

Example:

import time
time1 = time.time()
time.sleep(15)
time2 = time.time()
print time2 - time1
Copy after login

Among them, time.sleep() is the sleep function, unit: seconds.

2. Current time

>>> import datetime,time
>>> now = time.strftime("%Y-%m-%d %H:%M:%S")
>>> print now
2016-04-30 17:02:26
>>> now = datetime.datetime.now()
>>> print now
Copy after login

3. Time difference

#1 Yesterday 00:00 Until yesterday 23:59

>>> import datetime
>>> yestoday = datetime.datetime.now() - datetime.timedelta(days=1)
>>> t1 = "%s-00-00-00" % yestoday.strftime("%Y-%m-%d")
>>> t2 = "%s-23-59-59" % yestoday.strftime("%Y-%m-%d")
>>> print 't1', t1
t1 2016-04-29-00-00-00
>>> print 't2', t2
t2 2016-04-29-23-59-59
Copy after login

#2 Now 10 hours in the future

>>> d1 = datetime.datetime.now()
>>> d3 = d1 + datetime.timedelta(hours=10)
>>> d3.ctime()
'Sun May 1 03:09:58 2
Copy after login

#3 The number of seconds and microseconds for such a while (note that the seconds and microseconds are taken, not equivalent Conversion)

>>> import datetime
>>> starttime = datetime.datetime.now()
>>> endtime = datetime.datetime.now()
>>> starttime = datetime.datetime.now()
>>> endtime = datetime.datetime.now()
>>> print endtime - starttime
0:00:07.390988
>>> print (endtime - starttime).seconds
7
>>> print (endtime - starttime).microseconds
390988
Copy after login

Time stamp of the file

>>> import os
>>> statinfo=os.stat(r"C:/1.txt")
>>> statinfo
(33206, 0L, 0, 0, 0, 0, 29L, 1201865413, 1201867904, 1201865413)
Copy after login

Note: Use the return value of os.stat. The last three items in statinfo are the st_atime (access time), st_mtime (modification time) of the file, st_ctime (creation time), for example, get the file modification time:

>>> statinfo.st_mtime
1201865413.8952832
Copy after login

Note: This time is a linux timestamp, which can be converted into an easy-to-understand format:

>>> import time
>>> time.localtime(statinfo.st_ctime)
(2008, 2, 1, 19, 30, 13, 4, 32, 0)
Copy after login

Note: 19:30:13 on February 1, 2008 (2008-2-1 19:30:13)

##4. Time and date formatting symbols in python

%y Two-digit year representation (00-99) %Y Four-digit year representation (000-9999)
%m Month ( 01-12)
%d One day in the month (0-31)
%H 24-hour hour (0-23)
%I 12-hour hour (01-12)
%M Minutes (00=59)
%S Seconds (00-59)
%a Local simplified week name
%A Local complete week name
%b Local simplified month name
%B Local complete month name
%c Local corresponding date representation and time representation
%j Day within the year (
001-366) %p Local A.M. or Equivalent of P.M.
%U The number of weeks in a year (00-53) Sunday is the beginning of the week
%w The week (0-6), Sunday is the beginning of the week
%W Year The week number in (00-53) Monday is the beginning of the week
%x The corresponding local date representation
%X The corresponding local time representation
%Z The name of the current time zone
%% % The number itself

5. Example

#! coding:utf-8
''''' 日期相关的操作 '''
from datetime import datetime
from datetime import timedelta
import calendar
DATE_FMT = '%Y-%m-%d'
DATETIME_FMT = '%Y-%m-%d %H:%M:%S'
DATE_US_FMT = '%d/%m/%Y'
'''''
格式化常用的几个参数
Y : 1999
y :99
m : mouth 02 12
M : minute 00-59
S : second
d : day
H : hour
'''
def dateToStr(date):
  '''''把datetime类型的时间格式化自己想要的格式'''
  return datetime.strftime(date, DATETIME_FMT)
def strToDate(strdate):
  '''''把str变成日期用来做一些操作'''
  return datetime.strptime(strdate, DATETIME_FMT)
def timeElement():
  '''''获取一个时间对象的各个元素'''
  now = datetime.today()
  print 'year: %s month: %s day: %s' %(now.year, now.month, now.day)
  print 'hour: %s minute: %s second: %s' %(now.hour, now.minute, now.second)
  print 'weekday: %s ' %(now.weekday()+1) #一周是从0开始的
def timeAdd():
  '''''
  时间的加减,前一天后一天等操作
  datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
  参数可以是正数也可以是负数
  得到的对象可以加也可以减 乘以数字和求绝对值
  '''
  atime = timedelta(days=-1)
  now = datetime.strptime('2001-01-30 11:01:02', DATETIME_FMT)
  print now + atime
  print now - abs(atime)
  print now - abs(atime)*31
def lastFirday():
   today = datetime.today()
   targetDay = calendar.FRIDAY
   thisDay = today.weekday()
   de = (thisDay - targetDay) % 7
   res = today - timedelta(days=de)
   print res
def test():
  print dateToStr(datetime.today())
  print strToDate('2013-01-31 12:00:01')
  timeElement()
  timeAdd()
  lastFirday()
if name=='main':
  test()
Copy after login

Result

Connected to pydev debugger (build 141.1899)
2016-05-18 10:40:26
2013-01-31 12:00:01
year: 2016 month: 5 day: 18
hour: 10 minute: 41 second: 13
weekday: 3
2001-01-29 11:01:02
2001-01-29 11:01:02
2000-12-30 11:01:02
2016-05-13 10:41:37.001000
Copy after login

The above is the detailed content of Detailed introduction to Python timing related operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template