Detailed introduction to Python timing related operations
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
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
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
#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
#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
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)
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
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)
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()
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
