使用Python datetime()函数的7个实用示例
在本教程中,我们将学习pythondatetime()
模块。标准的" datetime"模块处理日期和时间。它定义了四个主要的对象类,每个类都有许多方法:
年,月,日的日期
时间(小时,分钟,秒和分数)
datetime
一起显示日期和时间用于日期和/或者时间间隔的" timedelta"
列出python datetime模块中的可用类
我们可以使用dir(datetime)
列出此模块下支持的操作,也可以使用相同的方法来检查datetime
函数的子模块支持的操作。
示例:从日期时间开始打印内置模块和子模块
在这个脚本中,我将只打印datetime()
和datetime.datetime()
模块的内容。
#!/usr/bin/env python3 # Import the datetime module import datetime # List sub modules (operations) under datetime module print("content of datetime module: ",dir(datetime)) # List operations under datetime.datetime sub module print("\ncontent of datetime.datetime submodule: ",dir(datetime.datetime))
该脚本的输出:
# python3 /tmp/datetime_ex.py content of datetime module: ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo'] content of datetime.datetime submodule: ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
使用datetime.now()
datetime.now()函数返回当前的本地日期和时间。我们可以将各种子模块与" datetime.now()"一起使用,以列出不同的值,例如月,年,日期等。
示例:从本地计算机获取当前日期和时间
在这个示例python脚本中,我们将打印datetime.now()
支持的不同操作
#!/usr/bin/env python3 import datetime # print current date and time based on the timezone from local machine print("Year: ",datetime.datetime.now().year) print("Month: ",datetime.datetime.now().month) print("Day: ",datetime.datetime.now().day) print("Hour: ",datetime.datetime.now().hour) print("Minute: ",datetime.datetime.now().minute) print("Second: ",datetime.datetime.now().second)
输出:
# python3 /tmp/datetime_ex.py Year: 2017 Month: 6 Day: 11 Hour: 8 Minute: 59 Second: 35
使用strftime()将Python datetime()转换为字符串格式
我们还可以通过使用strftime()
将来自datetime()
模块的输出格式化为字符串形式,该字符串的发音为f
ormattime。
我已经总结了一些最常用的代码格式,但是要获取符号的完整列表及其对datetime()
的含义,可以参考https://strftime.org/
参数 | 意义 | 范围 |
---|---|---|
%a | 工作日名称,短版本 | Sun |
%A | 工作日名称,完整版本 | Sunday |
%w | Weekday作为数字,0是星期日 | 0-6 |
%b | 月名,快照版本 | Jan |
%B | 月名,完整版本B | January |
%m | 月 | 01-12 |
%d | 月日 | 01-31 |
%Y | 四位数年份,完整版本 | 2019 |
%y | 两位数年份,短版本 | 19 |
%H | 小时,24小时格式 | 00-23 |
%I | 小时,12小时格式 | 01-12 |
%p | AM或者PM | AM,PM |
%M | 分钟 | 00-59 |
%S | 秒 | 00-59 |
%Z | 时区 | IST |
%c | 日期和时间的本地版本 | 周四2017年6月11日08:42:30 AM IST>/code> %xl时间的本地版本08:43:07 AM |
%x | 本地版本日期 | 06/11/2017 |
示例:使用strftime()格式化datetime()
在此脚本中,我们将使用strftime()
格式化不同的datetime.now()
值
sh<br>Thu 11 Jun 2017 08:42:30 AM IST>/code><br><br> %XLocal version of time08:43:07 AM<br>
输出:
#!/usr/bin/env python3 from datetime import datetime current_date_time = datetime.now() print("Current date and time: ",current_date_time) only_time = datetime.now().strftime("%H-%M-%S") print("Only Time output: ", only_time) only_date = datetime.now().strftime("%d-%m-%Y") print("Only Date output: ",only_date) date_and_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") print("Date and Time: ",date_and_time)
使用striptime()将Python字符串转换为datetime()
可以使用strptime()函数将字符串转换(解析)为datetime对象:
示例:转换字符串类型datetime()
在此脚本中,我们会将包含字符串类型值的" dateString"对象转换为" datetime()"类型值。
# python3 /tmp/datetime_ex.py Current date and time: 2017-06-20 16:19:00.766771 Only Time output: 16-19-00 Only Date output: 20-06-2017 Date and Time: 2017-06-20 16:19:00.767143
输出:
#!/usr/bin/env python3 import datetime # Define a string variable dateString = "20-06-2017" # Print and check the type of object for dateString print("Defined date string: ",dateString) print("Type of daeString object: ",type(dateString),"\n") # Convert to datetime type new_object = datetime.datetime.strptime(dateString, "%d-%m-%Y") # Print and check the type of new_object print("New object: ",new_object) print("Type of new_object: ",type(new_object))
Python日期时间时区
Python提供了两种完成时区转换的方式。使用"时间"内置模块的旧方法非常容易出错。新方法使用内置的" datetime"模块,在社区构建的名为" pytz"的软件包中提供了一些帮助,可以很好地工作。
示例:使用datetime.timezone()
在此脚本中,我们将时区从" datetime.now()"转换为UTC时区
# python3 /tmp/datetime_ex.py Defined date string: 20-06-2017 Type of daeString object: <class 'str'> New object: 2017-06-20 00:00:00 Type of new_object: <class 'datetime.datetime'>
我们还可以通过以下方式编写此脚本:仅从" datetime"模块中导入所需的子模块
#!/usr/bin/env python3 import datetime print("Local Date and Time: ",datetime.datetime.now()) print("Current Date and Time for UTC Timezone: ",datetime.datetime.now(datetime.timezone.utc))
输出:
#!/usr/bin/env python3 from datetime import datetime, timezone print("Local Date and Time: ",datetime.now()) print("Current Date and Time for UTC Timezone: ",datetime.now(timezone.utc))
示例:将datetime()与pytz()一起使用
在这个python脚本中,我将使用pytz()
模块而不是timezone()
来更改datetime.now()
中的时区值。
# python3 /tmp/datetime_ex.py Local Date and Time: 2017-06-20 15:31:34.638168 Current Date and Time for UTC Timezone: 2017-06-20 10:01:34.638245+00:00
该脚本的输出:
#!/usr/bin/env python3 from datetime import datetime import pytz # Store the timezone information in mytz object mytz = pytz.timezone('UTC') # print current date and time based on the timezone from local machine print("Local Date and Time: ",datetime.now()) # print current date and time from UTC timezone print("Current Date and Time for UTC Timezone: ",datetime.now(mytz))
示例:查找所有早于3天的文件
我们将编写一个小脚本,以在提供的路径下查找所有早于3天的文件。该脚本将从用户输入的目标位置中搜索文件。
# python3 /tmp/datetime_ex.py Local Date and Time: 2017-06-20 15:30:16.581239 Current Date and Time for UTC Timezone: 2017-06-20 10:00:16.581377+00:00
输出:
#!/usr/bin/env python3 import os import sys import datetime dirpath=input("Enter your path: ") if not os.path.exists(dirpath): print("Please provide valid path ") sys.exit(1) if os.path.isfile(dirpath): print("Please provide directory path ") sys.exit(2) # Create an object with current date and time todayDate = datetime.datetime.now() # Age reference required for comparison age = 3 # Run a loop for individual file found under dirpath object for myFile in os.listdir(dirpath): # Join the path along with the filename filePath=os.path.join(dirpath,myFile) # make sure the found element is a file if os.path.isfile(filePath): # use os.path.ctime to get creation details, or os.path.mtime for modification details # The value will be in seconds fileCrDate=os.path.getctime(filePath) # using fromtimestamp from datetime we get the difference by substracting from current date # Show only in days format from datetime module timeDiff=(todayDate - datetime.datetime.fromtimestamp(fileCrDate)).days # If the number of days in timeDiff is greater than provided age if timeDiff > age: print("No of day since",myFile,"was created:",timeDiff)