日常工作中,用 Python 处理时间格式的数据是非常常见的,今天就来分享 DateTime 相关的示例 。
1使用 time 模块展示当前日期和时间import timefrom time import gmtime, strftime t = time.localtime()print (time.asctime(t))print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))print(strftime("%A", gmtime()))print(strftime("%D", gmtime()))print(strftime("%B", gmtime()))print(strftime("%y", gmtime())) # Convert seconds into GMT dateprint(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))
Output:
Sun May 7 09:30:37 2017Sun, 07 May 2017 04:00:37 +0000Sunday05/07/17May17Fri, 13 Feb 2009 23:31:30 +0000
2将天、小时、分钟转换为秒SECONDS_PER_MINUTE= 60SECONDS_PER_HOUR= 3600SECONDS_PER_DAY= 86400 #Read the inputs from userdays= int(input("Enter number of Days: "))hours= int(input("Enter number of Hours: "))minutes = int(input("Enter number of Minutes: "))seconds = int(input("Enter number of Seconds: ")) #Calculate the days, hours, minutes and secondstotal_seconds = days * SECONDS_PER_DAYtotal_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)total_seconds = total_seconds + seconds #Display the resultprint("Total number of seconds: ","%d"%(total_seconds))
Output:
Enter number of Days: 5Enter number of Hours: 36Enter number of Minutes: 24Enter number of Seconds: 15Total number of seconds: 563055
3使用 Pandas 获取当前日期和时间import pandas as pdprint(pd.datetime.now())print(pd.datetime.now().date())print(pd.datetime.now().year)print(pd.datetime.now().month)print(pd.datetime.now().day)print(pd.datetime.now().hour)print(pd.datetime.now().minute)print(pd.datetime.now().second)print(pd.datetime.now().microsecond)
Output:
2018-01-19 16:08:28.3935532018-01-19201811916828394553
4将字符串转换为日期时间对象from datetime import datetimefrom dateutil import parserd1 = "Jan 7 20151:15PM"d2 = "2015 Jan 71:33PM"# If you know date formatdate1 = datetime.strptime(d1, '%b %d %Y %I:%M%p')print(type(date1))print(date1)# If you don't know date formatdate2 = parser.parse(d2)print(type(date2))print(date2)
Output:
class 'datetime.datetime'2015-01-07 13:15:00class 'datetime.datetime'2015-01-07 13:33:00
5以毫秒为单位获取当前时间import time milliseconds = int(round(time.time() * 1000))print(milliseconds)
Output:
1516364270650
6以 MST、EST、UTC、GMT 和 HST 获取当前日期时间from datetime import datetimefrom pytz import timezone mst = timezone('MST')print("Time in MST:", datetime.now(mst)) est = timezone('EST')print("Time in EST:", datetime.now(est)) utc = timezone('UTC')print("Time in UTC:", datetime.now(utc)) gmt = timezone('GMT')print("Time in GMT:", datetime.now(gmt)) hst = timezone('HST')print("Time in HST:", datetime.now(hst))
Output:
Time in MST: 2017-01-19 06:06:14.495605-07:00Time in EST: 2017-01-19 08:06:14.496606-05:00Time in UTC: 2017-01-19 13:06:14.496606+00:00Time in GMT: 2017-01-19 13:06:14.496606+00:00Time in HST: 2017-01-19 03:06:14.497606-10:00
7从给定的日期当中获取星期几import datetime dayofweek = datetime.date(2010, 6, 16).strftime("%A")print(dayofweek)# weekday Monday is 0 and Sunday is 6print("weekday():", datetime.date(2010, 6, 16).weekday()) # isoweekday() Monday is 1 and Sunday is 7print("isoweekday()", datetime.date(2010, 6, 16).isoweekday()) dayofweek = datetime.datetime.today().strftime("%A")print(dayofweek)print("weekday():", datetime.datetime.today().weekday())print("isoweekday()", datetime.datetime.today().isoweekday())
Output:
Wednesdayweekday(): 2isoweekday() 3Fridayweekday(): 4isoweekday() 5
8计算两个日期时间对象之间的时差import datetimefrom datetime import timedelta datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'date1 = '2016-04-16 10:01:28.585'date2 = '2016-03-10 09:56:28.067'diff = datetime.datetime.strptime(date1, datetimeFormat)- datetime.datetime.strptime(date2, datetimeFormat) print("Difference:", diff)print("Days:", diff.days)print("Microseconds:", diff.microseconds)print("Seconds:", diff.seconds)
Output:
Difference: 37 days, 0:05:00.518000Days: 37Microseconds: 518000Seconds: 300
9将 5 分钟添加到 Unix 时间戳import datetimeimport calendar future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)print(calendar.timegm(future.timetuple()))
Output:
1621069619
10在 Python 中遍历一系列日期
推荐阅读
- DOS批处理命令:for循环详细说明及例子
- 15个Python入门小程序,你都知道哪些
- 运维需要掌握的 17 个实用技巧
- c#读写SQLite数据库文件例子
- 一文掌握SQL基础
- 这举动掌握好频率才有最大的好处
- MySQL中常用的15个查询子句
- 前端开发中需要掌握的开发框架React
- 这27个常用Linux命令,我建议大家都熟练掌握,工作中够用了
- 15个MySQL常用基本SQL语句