def statuses(twitter, screen_name, tweets, mentions=False, favorites=False, received_dms=None, isoformat=False): """Get all the statuses for a screen name.""" max_id = None fail = Fail() # get portions of statuses, incrementing max id until no new tweets appear while True: try: portion = statuses_portion(twitter, screen_name, max_id, mentions, favorites, received_dms, isoformat) except TwitterError as e: if e.e.code == 401: err("Fail: %i Unauthorized (tweets of that user are protected)" % e.e.code) break elif e.e.code == 400: err("Fail: %i API rate limit exceeded" % e.e.code) rate = twitter.account.rate_limit_status() reset = rate['reset_time_in_seconds'] reset = time.asctime(time.localtime(reset)) delay = int(rate['reset_time_in_seconds'] - time.time()) + 5 # avoid race err("Hourly limit of %i requests reached, next reset on %s: " "going to sleep for %i secs" % (rate['hourly_limit'], reset, delay)) fail.wait(delay) continue elif e.e.code == 404: err("Fail: %i This profile does not exist" % e.e.code) break elif e.e.code == 502: err("Fail: %i Service currently unavailable, retrying..." % e.e.code) else: err("Fail: %s\nRetrying..." % str(e)[:500]) fail.wait(3) except urllib2.URLError as e: err("Fail: urllib2.URLError %s - Retrying..." % str(e)) fail.wait(3) except httplib.error as e: err("Fail: httplib.error %s - Retrying..." % str(e)) fail.wait(3) except KeyError as e: err("Fail: KeyError %s - Retrying..." % str(e)) fail.wait(3) else: new = -len(tweets) tweets.update(portion) new += len(tweets) err("Browsing %s statuses, new tweets: %i" % (screen_name if screen_name else "home", new)) if new < 190: break max_id = min(portion.keys()) - 1 # browse backwards fail = Fail()
def rate_limit_status(twitter): """Print current Twitter API rate limit status.""" r = twitter.account.rate_limit_status() print("Remaining API requests: %i/%i (hourly limit)" % (r['remaining_hits'], r['hourly_limit'])) print("Next reset in %is (%s)" % (int(r['reset_time_in_seconds'] - time.time()), time.asctime(time.localtime(r['reset_time_in_seconds']))))
def statuses(twitter, screen_name, tweets, mentions=False, favorites=False, received_dms=None, isoformat=False): """Get all the statuses for a screen name.""" max_id = None fail = Fail() # get portions of statuses, incrementing max id until no new tweets appear while True: try: portion = statuses_portion(twitter, screen_name, max_id, mentions, favorites, received_dms, isoformat) except TwitterError as e: if e.e.code == 401: err("Fail: %i Unauthorized (tweets of that user are protected)" % e.e.code) break elif e.e.code == 400: err("Fail: %i API rate limit exceeded" % e.e.code) rate = twitter.account.rate_limit_status() reset = rate['reset_time_in_seconds'] reset = time.asctime(time.localtime(reset)) delay = int(rate['reset_time_in_seconds'] - time.time()) + 5 # avoid race err("Hourly limit of %i requests reached, next reset on %s: " "going to sleep for %i secs" % (rate['hourly_limit'], reset, delay)) fail.wait(delay) continue elif e.e.code == 404: err("Fail: %i This profile does not exist" % e.e.code) break elif e.e.code == 502: err("Fail: %i Service currently unavailable, retrying..." % e.e.code) else: err("Fail: %s\nRetrying..." % str(e)[:500]) fail.wait(3) except urllib2.URLError as e: err("Fail: urllib2.URLError %s - Retrying..." % str(e)) fail.wait(3) except httplib.error as e: err("Fail: httplib.error %s - Retrying..." % str(e)) fail.wait(3) except KeyError as e: err("Fail: KeyError %s - Retrying..." % str(e)) fail.wait(3) else: new = -len(tweets) tweets.update(portion) new += len(tweets) err("Browsing %s statuses, new tweets: %i" % (screen_name if screen_name else "home", new)) if new < 190: break max_id = min(portion.keys())-1 # browse backwards fail = Fail()
def time_turn(): localtime = time.asctime(time.localtime()) print("当前默认日期时间格式:%s" % localtime) print(type(localtime)) # 格式化为:年-月-日 时:分:秒 星期几 print("24小时制全格式:", time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime())) print("12小时制缩写格式:", time.strftime("%Y-%m-%d %I:%M:%S %a", time.localtime())) # 带a.m. 或 p.m. 标识时间格式 %p print("带a.m或p.m 24小时制全格式:", time.strftime("%Y-%m-%d %H:%M:%S %p %A", time.localtime())) # 把时区也带上看看 %z print("带时区的全格式:", time.strftime("%Y-%m-%d %H:%M:%S %p %A %z", time.localtime())) # 格式乱排下试试 print("随意排格式:", time.strftime("%A %Y-%d-%m %p %H:%M:%S %z", time.localtime()))
def playbook_on_stats(self, stats): """ Prints the timings """ if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None: return # Record the timing of the very last task if self.current is not None: self.stats[self.current] = time.time() - self.stats[self.current] # Sort the tasks by their running time results = sorted( self.stats.items(), key=lambda value: value[1], reverse=True, ) # Just keep the top 10 results = results[:10] # Print the timings for name, elapsed in results: print( "{0:-<70}{1:->9}".format( '{0} '.format(name), ' {0:.02f}s'.format(elapsed), ) ) total_seconds = sum([x[1] for x in self.stats.items()]) print("\nPlaybook finished: {0}, {1} total tasks. {2} elapsed. \n".format( time.asctime(), len(self.stats.items()), datetime.timedelta(seconds=(int(total_seconds))) ) )
date:日期类,包括属性年、月、日及相关方法 time:时间类,包括属性时、分、秒等及相关方法 datetime:日期时间,继承于 date,包括属性年、月、日、时、分、秒等及相关方法,其中年月日必须参数 timedelta:两个 datetime 值的差,比如相差几天(days)、几小时(hours)、几分(minutes)等。 除了以上 2 个时间模块外,calendar 模块还提供一些实用的功能,比如: 年、月的日历图 闰年判断 月有几天等等 ''' import time seconds = time.time() print(seconds) local_time = time.localtime() print(local_time) str_time = time.asctime(local_time) print(str_time) format_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time) print(format_time) # time 类 strptime 方法,解析( parse) 输入的时间字符串为 struct_time 类型的时间。 # 注意:第二个参数的时间格式,要匹配上第一个参数的时间格式。 str_to_struct = time.strptime(format_time, '%Y-%m-%d %H:%M:%S') print(str_to_struct) ''' 记住常用的时间格式: %Y 年 %m 月 取值 [01,12] %d 天 取值 [01,31] %H 小时 取值 [00,23] %M 分钟 取值 [00,59] %S 秒 取值 [00,61]
%M 分钟数(00=59) %S 秒(00-59) %a 简写的星期名称 %A 完整星期名称 %b 简写的月份名称 %B 完整的月份名称 %c 相应的日期表示和时间表示 %j 年内的一天(001-366) %p A.M.或P.M.的等价符 %U 一年中的星期数(00-53)星期天为星期的开始 %w 星期(0-6),星期天为星期的开始 %W 一年中的星期数(00-53)星期一为星期的开始 %x 相应的日期表示 %X 相应的时间表示 %z 当前时区的名称 %% %号本身 """ #先查看当前默认格式化显示的时间 localtime=time.asctime(time.localtime()) print("当前默认日期时间格式是:%s"% localtime) # 格式化为: 年-月-日 时:分:秒 星期几 print("24小时制全格式:", time.strftime("%Y-%m-%d %H:%M:%S %A",time.localtime())) print("12小时制缩写格式:", time.strftime("%Y-%m-%d %H:%M:%S %a", time.localtime())) #带a.m 或p.m标识时间%p print("带a.m 或p.m24小时制全格式:",time.strftime("%Y-%m-%d %H:%M:%S %p %A",time.localtime())) # 把时区也带上看看 %z print("带时区的全格式:", time.strftime("%Y-%m-%d %H:%M:%S %p %A %z", time.localtime())) # 格式乱排下试试 print("随意排格式:", time.strftime("%A %Y-%d-%m %p %H:%M:%S %z", time.localtime()))
d = datetime(year=2008,month=8,day=8,minute=8,second=8) print ('造的日期时间为:%s'%d) ''' 格式化日期时间:strftime 函数 常用的时间格式如下: %y 两位数的年份(00-99) %Y 四位数的年份(000-9999) %m 月份(01-12) %d 月内的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制的小时数(01-12) %M 分钟数(00-59) %S 秒(00-59) ''' #当前默认格式化时间: import time t = time.localtime() print ('未格式化前的时间:t = %s'%t) print (u'当前默认日期时间格式:%s'%time.asctime(t)) #格式化为:年-月-日 时:分:秒 星期几 print (u'24小时制全格式:',time.strftime('%Y-%m-%d %H:%M:%S %A'),time.localtime()) print (u'12小时制缩写格式:',time.strftime('%Y-%m-%d %I:%M:%S %a',time.localtime())) #带a.m 或p.m 24小时制格式: print ("带a.m或p.m 24小时制全格式:",time.strftime("%Y-%m-%d %H:%M:%S %p %A",time.localtime())) #格式乱排序: print ('随意拍格式:',time.strftime("%A %Y-%d-%m %p %H:%M:%S %z",time.localtime()))
# 用time构造时间 # t = time(hour=20, minute=15, second=2, microsecond=30) # print("构造时间: %s" % t) # 用datetime构造日期+时间 d = datetime(year=2018, month=3, day=7, hour=19, minute=0, second=0, microsecond=200) print("构造 日期+时间: %s" % d) # 默认格式化时间 localtime = time.asctime(time.localtime()) print("默认时间格式: %s" % localtime) # 格式化为:年-月-日 时:分:秒 星期几 print("24小时格式化:", time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime())) print("12小时格式化:", time.strftime("%Y-%m-%d %I:%M:%S %a", time.localtime())) # 带a.m. 或 p.m. 表示时间格式 %p print("带a.m. 或 p.m.24小时格式:", time.strftime("%Y-%m-%d %H:%M:%S %p %A", time.localtime())) # 把时区也带上 %z print("带时区的时间格式: ", time.strftime("%Y-%m-%d %H:%M:%S %p %A %z", time.localtime()))
kurang = a - b return kurang def kali(a, b): kali = a * b return kali def bagi(a, b): bagi = a / b return bagi while True: jamLokal = time.asctime(time.localtime(time.time())) jam = time.localtime().tm_hour jamLokal = time.asctime(time.localtime(time.time())) jam = time.localtime().tm_hour print("=" * 60 + "\n" + "=" * 24 + "-|" + "Kalkulator" + "|-" + "=" * 22) print("=" * 16 + "-|" + jamLokal + "|-" + "=" * 16) if 0 <= jam <= 6: print("=" * 21 + "-<|Selamat Subuh|>-" + "=" * 20) elif 6 <= jam <= 12: print("=" * 21 + "-<|Selamat Pagi|>-" + "=" * 21) elif 12 <= jam <= 14: print("=" * 21 + "-<|Selamat Siang|>-" + "=" * 20)
#再造个日期时间出来试试: d = datetime(year=2008, month=8, day=8, minute=8, second=8) print('造的日期时间为:%s' % d) ''' 格式化日期时间:strftime 函数 常用的时间格式如下: %y 两位数的年份(00-99) %Y 四位数的年份(000-9999) %m 月份(01-12) %d 月内的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制的小时数(01-12) %M 分钟数(00-59) %S 秒(00-59) ''' #当前默认格式化时间: import time t = time.localtime() print('未格式化前的时间:t = %s' % t) print(u'当前默认日期时间格式:%s' % time.asctime(t)) #格式化为:年-月-日 时:分:秒 星期几 print(u'24小时制全格式:', time.strftime('%Y-%m-%d %H:%M:%S %A'), time.localtime()) print(u'12小时制缩写格式:', time.strftime('%Y-%m-%d %I:%M:%S %a', time.localtime())) #带a.m 或p.m 24小时制格式: print("带a.m或p.m 24小时制全格式:", time.strftime("%Y-%m-%d %H:%M:%S %p %A", time.localtime())) #格式乱排序: print('随意拍格式:', time.strftime("%A %Y-%d-%m %p %H:%M:%S %z", time.localtime()))
>>> >>> import time >>> import sys >>> print(sys.version) 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] >>> >>> print(time.perf_counter(), time.localtime(time.perf_counter())) 89.4915672 time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=1, tm_sec=29, tm_wday=3, tm_yday=1, tm_isdst=0) >>> >>> import time >>> time.time() 1614326427.3598132 >>> time.localtime(time.time()) time.struct_time(tm_year=2021, tm_mon=2, tm_mday=26, tm_hour=9, tm_min=0, tm_sec=57, tm_wday=4, tm_yday=57, tm_isdst=0) >>> time.asctime(time.localtime(time.time())) 'Fri Feb 26 09:01:38 2021' >>> time.localtime(time.clock()) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> time.localtime(time.clock()) AttributeError: module 'time' has no attribute 'clock' >>> time.localtime(time.clock())) SyntaxError: unmatched ')' >>> import calendar >>> calendar.month(2021, 7) ' July 2021\nMo Tu We Th Fr Sa Su\n 1 2 3 4\n 5 6 7 8 9 10 11\n12 13 14 15 16 17 18\n19 20 21 22 23 24 25\n26 27 28 29 30 31\n' >>> calendar.month(2021, 7, w=1, l=2) ' July 2021\n\nMo Tu We Th Fr Sa Su\n\n 1 2 3 4\n\n 5 6 7 8 9 10 11\n\n12 13 14 15 16 17 18\n\n19 20 21 22 23 24 25\n\n26 27 28 29 30 31\n\n' >>> calendar.setfirstweekday(6)
def new_names(folder): name_of_file = time.asctime().replace(':', "-") file_name = folder + name_of_file + '.png' return file_name
#14. Write a Python program to find the date of the first Monday of a given week. Sample Year and week: 2015, 50. Expected Output: Mon Dec 14 00:00:00 2015. #source: https://stackoverflow.com/questions/17087314/get-date-from-week-number. https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior. sampleyear = 2015 sampleweek = 50 sampleyearweek = "2015, 50" firstmonday = datetime.strptime(sampleyearweek + "-1", "%Y, %W-%w") print(firstmonday) #print 2015-12-14 00:00:00 print(firstmonday.strftime("%a %b %d %Y")) #print Mon Dec 14 2015 firsttuesday = datetime.strptime(sampleyearweek + "-2", "%Y, %W-%w") print(firsttuesday) #print 2015-12-15 00:00:00 print(firsttuesday.strftime("%a %b %d %Y")) #print Tue Dec 15 2015 firstsaturday = datetime.strptime(sampleyearweek + "-6", "%Y, %W-%w") print(firstsaturday) #print 2015-12-19 00:00:00 print(firstsaturday.strftime("%a %b %d %Y")) #print Sat Dec 19 2015 #official solution import time print(time.asctime(time.strptime('2015 50 1', '%Y %W %w'))) #print Mon Dec 14 00:00:00 2015 #15. Write a Python program to select all the Sundays of a specified year. year = str(2015) for n in range(0, 53): weekstring = str(n) yearweek = year + " " + weekstring sundays = datetime.strptime(yearweek + "-0", "%Y %W-%w") print(sundays.strftime( "%a %b %d %Y")) #print Sun Jan 04 2015 . . . Sun Jan 03 2016 #16. Write a Python program to add year(s) with a given date and display the new date. """ Sample Data: (addYears is the user defined function name) print(addYears(datetime.date(2015,1,1), -1)) print(addYears(datetime.date(2015,1,1), 0))