15个例子,掌握Python日期时间处理

日常工作中,用 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 +00002将天、小时、分钟转换为秒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: 5630553使用 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-192018119168283945534将字符串转换为日期时间对象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:005以毫秒为单位获取当前时间import time milliseconds = int(round(time.time() * 1000))print(milliseconds)Output:
15163642706506以 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:007从给定的日期当中获取星期几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() 58计算两个日期时间对象之间的时差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: 3009将 5 分钟添加到 Unix 时间戳import datetimeimport calendar future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)print(calendar.timegm(future.timetuple()))Output:
162106961910在 Python 中遍历一系列日期


推荐阅读