time module
The time module is a function that contains various operations on time. Although these are often valid, not all methods are valid on all platforms. Time uses struct_time Represents time
import time
# time.struct_time(tm_year=2015, tm_mon=4, tm_mday=24,
tm_hour=14, tm_min=17, tm_sec=26,
tm_wday=4, tm_yday=114, tm_isdst=0)
# 2015
print time.localtime()
print time.localtime().tm_year
Function
time.time(): Returns a timestamp
time.asctime([t]): Convert the tuple or struct_time returned by gmtime() and localtime() to string.
time.clock(): When called for the first time, return the time when the program is running. After the second call, return the interval from before.
time.ctime([secs]) : Convert the timestamp to a time string. If not provided, the current time string is returned, which is the same as asctime(localtime()).
time.gmtime([secs] ): Convert timestamp to struct_time in UTC time zone.
-
time.localtime([secs]): Similar to gmtime() but will convert it to local time zone.
time.mktime(t): struct_time is converted into a timestamp.
time.sleep(secs): The thread delays the specified time, in seconds .
time.strftime(format[,t]): Convert a sturc_time or tuple to a string according to the parameters.
time. strptime(string[, format]): Contrary to strftime, returns a struct_time.
##
import time # Fri Apr 24 06:39:34 2015 print time.asctime(time.gmtime()) # 0.0 # None # 1.01136392961 因计算机而异 print time.clock() print time.sleep(1) print time.clock() # Fri Apr 24 14:42:07 2015 print time.ctime() # 2015-04-24 print time.strftime('%Y-%m-%d', time.localtime()) # 1429857836.0 print time.mktime(time.localtime())
commonly used in the time module Format string
- %y Two-digit year 00 ~ 99.
- %Y Four-digit year 0000 ~ 9999
- %m month 01 ~ 12.
- %d day 01 ~ 31.
- %H Hours 00 ~ 23.
- %I Hours 01 ~ 12. ##%M Minutes 00 ~ 59.
- %S seconds 00 ~ 61.
datetime module
datetime module provides date Perform simple or complex operations with time. The datetime module provides the following available types (Available Types).datetime.MINYEAR and datetime.MAXYEAR module constants represent the range accepted by datetime
- class datetime.date: An idealized date, providing year, month, and day attributes
- class datetime.time: An idealized time, providing hour, minute, second, microsecond, tzinfo.
- class datetime.datetime: A combination of date and time. Provides year, month, day, hour, minute, second, microsecond, tzinfo.
- class datetime.timedelta: Express the subtle difference between the duration of two dates, time and datetime.
- class datetime.tzinfo: The abstract base of time objects Class.
from datetime import timedelta, datetime a = datetime.now() b = timedelta(days=7) # 7 days, 0:00:00 # 2015-04-14 16:02:39.189000 print b print a - b
Let’s talk about classes and class methods in detail
date classA date object represents an idealized date.
class datetime.date(year, month, day)
# All arguments are required. Arguments may be ints or longs.
# 所有参数都是必须的. 参数可能是 int 或 long.
MINYEAR <= year <= MAXYEAR
1<= month <= 12
1<= day <= number of days in the given month and year.(随着月份和年份)
If the parameter is outside the given range, valueError will be thrown.
1. Class method>`date.today()`: Return the current local date, which is equivalent to `date.fromtimestamp(time.time())`.
Return the current local date. This is equivalent to `date.fromtimestamp(time.time())`.from datetime import date # print 2015-04-21 print date.today()
2.date.fromtimestamp(timestamp):According to the provided Timestamp returns local date. Timestamp is often used to store time types.
import time from datetime import date # 1429587111.21 # 2015-04-21 print time.time() print date.fromtimestamp(time.time())
3. Class method date.fromordinal(ordinal): According to the provided Gregorian Calendar returns date.(No description)
Class attribute
- date.min: Returns date(MINYEAR, 1, 1).
- date.max: Returns date(MAXYEAR, 12, 31).
- date.year: Returns the year, between MINYEAR and MAXYEAR
- date.month: Returns the month, between 1 and December
- date.day: Returns between 1 and n.
d = date(2014, 4, 21) # 2014 4 21 print d.year, d.month, d.day
Instance method
- date.replace(year, month, day): Returns a data object with the same value, except These parameters specify new values for keywords.
- date.timetuple(): Returns a time.struct_time object.
- date.toordinal (): Returns a Gregoian Calendar object.
- date.weekday(): Returns the day of the week. Monday is 0, Sunday is 6.
- date.isoweekday(): Returns the day of the week. Monday is 1, Sunday is 7.
- date.isocalendar(): Returns a triple, ( ISO year, ISO week number, ISO weekday).
- date.isoformat(): Returns a string format of 'YYYY-MM-DD'.
- date.ctime(): Returns a string date, d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())).
- date.strftime(format): Returns a string date with custom format.
- ##
d = date(2015, 4, 21) # 2015-04-21 # 2015-04-21 # 2015-04-22 print d print d.replace() print d.replace(day=22) # time.struct_time(tm_year=2015, tm_mon=4, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=111, tm_isdst=-1) print d.timetuple() # print 1 # print 2 print d.weekday() print d.isoweekday() # print 2015-04-21 print d.isoformat() # print 21/04/2015 print d.strftime('%d/%m/%y')
datetime class
The datetime object is a single object that contains information about all date and time objects.
class datetime.datetime(year, month, day[, hour
[, minute
[, second
[, microsecond
[, tzinfo]]]]])
# The year, month and day arguments are required.
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= n
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 10**6
Class method
datetime.today(): Returns the current local datetime. With tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()).datetime.now([tz]): 返回当前本地日期和时间, 如果可选参数tz为None或没有详细说明,这个方法会像today().
datetime.utcnow(): 返回当前的UTC日期和时间, 如果tzinfo None ,那么与now()类似.
datetime.fromtimestamp(timestamp[, tz]): 根据时间戳返回本地的日期和时间.tz指定时区.
datetime.utcfromtimestamp(timestamp): 根据时间戳返回 UTC datetime.
datetime.fromordinal(ordinal): 根据Gregorian ordinal 返回datetime.
datetime.combine(date, time): 根据date和time返回一个新的datetime.
datetime.strptime(date_string, format): 根据date_string和format返回一个datetime.
from datetime import datetime # 2015-04-21 14:07:39.262000 print datetime.today() # 2015-04-21 14:08:20.362000 print datetime.now() # 1429596607.06 # 2015-04-21 14:10:07.061000 t = time.time() print t print datetime.fromtimestamp(t) from datetime import datetime, date, time a = date(2015, 4, 21) b = time(14, 13, 34) # 2015-04-21 14:13:34 print datetime.combine(a, b)
实例方法
datetime.date(): 返回相同年月日的date对象.
datetime.time(): 返回相同时分秒微秒的time对象.
datetime.replace(kw): kw in [year, month, day, hour, minute, second, microsecond, tzinfo], 与date类似.
其他方法可查看官方文档…
from datetime import datetime, date, time td = date(2015, 4, 21) n = time(14, 28, 30) # 2099-04-21 14:30:42.103000 print datetime.now(0.replace(year=2099)
类属性
datetime.min: datetime(MINYEAR, 1, 1).
datetime.max: datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999).
实例属性(read-only)
datetime.year: 1 至 9999
datetime.month: 1 至 12
datetime.day: 1 至 n
datetime.hour: In range(24). 0 至 23
datetime.minute: In range(60).
datetime.second: In range(60).
datetime.microsecond: In range(1000000).
time类
time 代表本地(一天内)时间.
class datetime.time([hour
[, minute
[, second
[, microsecond
[, tzinfo]]]]])
# All arguments are optional.
# 所有参数都是可选的.
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsesond < 10**6
time类就是对时间的一些操作,其功能类似与datetime.其实date和time就是对datetime中日期和时间的操作.
更多Python中的time模块与datetime模块相关文章请关注PHP中文网!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),






