第12.5节 Python time模块导览

本文深入讲解了Python中time模块的功能,包括时间的概念、主要函数如asctime、ctime、gmtime等的使用方法,以及如何处理时间戳、格式化时间和解析时间字符串。同时,文章还提到了时间处理中的常见问题,如2000年问题和夏令时的处理。

一、时间相关的概念
time模块模块提供了各种时间相关的函数,在介绍时间相关功能前,先介绍一些术语和惯例:

  1. epoch 是时间开始的点,并且取决于平台。对于Unix, epoch 是1970年1月1日00:00:00(UTC)。要找出给定平台上的 epoch ,请查看 time.gmtime(0) 。
  2. 术语 Unix 纪元秒数 是指自国际标准时间 1970 年 1 月 1 日零时以来经过的总秒数,通常不包括 闰秒。 在所有符合 POSIX 标准的平台上,闰秒都会从总秒数中被扣除。
  3. time模块中的功能可能无法处理纪元之前或将来的远期日期和时间。未来的截止点由C库决定;对于32位系统,它通常在2038年。
  4. 2000年(Y2K)问题 :Python依赖于平台的C库,它通常没有2000年问题,因为所有日期和时间都在内部表示为自纪元以来的秒数。函数 strptime() 在给出 %y 格式代码时可以解析2位数年份。当解析2位数年份时,它们将根据 POSIX 和 ISO C 标准进行转换:值 69–99 映射到 1969–1999,值 0–68 映射到2000–2068。
  5. UTC是协调世界时(以前称为格林威治标准时间,或GMT)。缩写UTC不是错误,而是英语和法语之间的妥协。
  6. DST是夏令时,在一年中的一部分时间(通常)调整时区一小时。 DST规则很神奇(由当地法律确定),并且每年都会发生变化。 C 库有一个包含本地规则的表(通常是从系统文件中读取以获得灵活性),并且在这方面是True Wisdom的唯一来源。
  7. 各种实时函数的精度可能低于表示其值或参数的单位所建议的精度。例如,在大多数Unix系统上,时钟 “ticks” 仅为每秒50或100次。

二、time模块的主要功能

  1. time.asctime([t]):转换一个元组或 struct_time 表示的时间t,由 gmtime() 或 localtime() 返回为以下形式的字符串: ‘Wed Aug 7 11:21:16 2019’ 。如果未提供 t ,则使用由 localtime() 返回的当前时间。
  2. time.ctime([secs]):将自 epoch以来的秒数 表示的时间转换为表示本地时间的字符串。如果未提供 secs 或为 None,则使用由 time() 返回的当前时间。 ctime(secs) 相当于 asctime(localtime(secs)) 。
  3. time.gmtime([secs]):将 自 epoch以来的秒数表示的时间转换为UTC的 struct_time ,如果未提供 secs 或为 None ,则使用由 time() 返回的当前时间。
  4. time.localtime([secs]):与 gmtime() 相似但转换为当地时间。如果未提供 secs 或为 None ,则使用由 time() 返回的当前时间。
  5. time.mktime(t):这是 localtime() 的反函数。它的参数是 struct_time 或者完整的 9 元组,它表示 本地时间,而不是 UTC 。
  6. time.process_time():返回当前进程的系统和用户CPU时间总和的值(以小数秒为单位)。它不包括睡眠期间经过的时间。根据定义,它在整个进程范围中。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。
  7. time.sleep(secs):休眠secs秒,参数可以是浮点数,以指示更精确的睡眠时间。实际的暂停时间可能小于请求的时间,因为任何捕获的信号将在执行该信号的捕获例程后终止 sleep() 。。
  8. time.strftime(format[, t]):转换一个元组或 struct_time 表示的由 gmtime() 或 localtime() 返回的时间到由 format 参数指定的字符串。如果未提供 t ,则使用由 localtime() 返回的当前时间。 format 必须是一个字符串。如:
>>> "{}".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))		
'2019-08-07 11:30:53'
>>> 

  1. time.strptime(string[, format]):根据格式解析表示时间的字符串。 返回值为一个被 gmtime() 或 localtime() 返回的 struct_time 。format 参数使用与 strftime()使用的指令相同的指令。它默认为匹配 ctime() 返回格式的 “%a %b %d %H:%M:%S %Y”` 。

关于时间的模块还有datetime和calendar,在此不在介绍,大家自行查询相关文档。

老猿Python,跟老猿学Python!
博客地址:https://blog.youkuaiyun.com/LaoYuanPython

请大家多多支持,点赞、评论和加关注!谢谢!

#!/usr/bin/env python #coding: utf-8 import rospy from geometry_msgs.msg import Point import threading import actionlib import time from actionlib_msgs.msg import GoalStatus from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from geometry_msgs.msg import PoseWithCovarianceStamped from tf_conversions import transformations from ar_track_alvar_msgs.msg import AlvarMarkers from math import pi from std_msgs.msg import String import sys reload(sys) sys.setdefaultencoding('utf-8') class Navigation: def __init__(self): self.set_pose_pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped, queue_size=5) self.move_base = actionlib.SimpleActionClient("move_base", MoveBaseAction) self.move_base.wait_for_server(rospy.Duration(60)) def set_pose(self, p): if self.move_base is None: return False x, y, th = p pose = PoseWithCovarianceStamped() pose.header.stamp = rospy.Time.now() pose.header.frame_id = 'map' pose.pose.pose.position.x = x pose.pose.pose.position.y = y q = transformations.quaternion_from_euler(0.0, 0.0, th/180.0*pi) pose.pose.pose.orientation.x = q[0] pose.pose.pose.orientation.y = q[1] pose.pose.pose.orientation.z = q[2] pose.pose.pose.orientation.w = q[3] self.set_pose_pub.publish(pose) return True def _feedback_cb(self, feedback): msg = feedback #rospy.loginfo("[Navi] navigation feedback\r\n%s"%feedback) def goto(self, p): rospy.loginfo("[Navigation] goto %s"%p) goal = MoveBaseGoal() goal.target_pose.header.frame_id = 'map' goal.target_pose.header.stamp = rospy.Time.now() goal.target_pose.pose.position.x = p[0] goal.target_pose.pose.position.y = p[1] q = transformations.quaternion_from_euler(0.0, 0.0, p[2]/180.0*pi) goal.target_pose.pose.orientation.x = q[0] goal.target_pose.pose.orientation.y = q[1] goal.target_pose.pose.orientation.z = q[2] goal.target_pose.pose.orientation.w = q[3] self.move_base.send_goal(goal, self._done_cb, self._active_cb, self._feedback_cb) result = self.move_base.wait_for_result(rospy.Duration(60)) if not result: self.move_base.cancel_goal() rospy.loginfo("Timed out achieving goal") else: state = self.move_base.get_state() if state == GoalStatus.SUCCEEDED: rospy.loginfo("reach goal %s succeeded!"%p) return True def _done_cb(self, status, result): rospy.loginfo("navigation done! status:%d result:%s"%(status, result)) def _active_cb(self): rospy.loginfo("[Navi] navigation has be actived") def cancel(self): self.move_base.cancel_all_goals() return True class ARTracker: def __init__(self): self.ar_sub = rospy.Subscriber('/ar_pose_marker', AlvarMarkers, self.ar_cb) def ar_cb(self,data): global tag_id for marker in data.markers: tag_id = marker.id class Object_position: def __init__(self): self.ar_sub = rospy.Subscriber('/object_position', Point, self.find_cb) self.tts_pub = rospy.Publisher('/voiceWords', String, queue_size=10) def find_cb(self,data): global find_id point_msg = data if(point_msg.z>=1 and point_msg.z<=5): find_id = 1 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=9 and point_msg.z<=15): find_id = 2 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=16 and point_msg.z<=23): find_id = 3 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=25 and point_msg.z<=26): find_id = 4 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=36 and point_msg.z<=40): find_id = 5 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=41 and point_msg.z<=43): find_id = 6 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=70 and point_msg.z<=71): find_id = 7 self.tts_pub.publish(str(find_id)) elif(point_msg.z>=80 and point_msg.z<=81): find_id = 8 self.tts_pub.publish(str(find_id)) else: find_id = 0 #print("id为0,没有识别到!") def process(): rospy.spin() find_id = 0 tag_id = 0 both_id =0 if __name__ == '__main__': rospy.init_node('navigation_demo',anonymous=True) goalListX = rospy.get_param('~goalListX', '2.0, 2.0,2.0') goalListY = rospy.get_param('~goalListY', '2.0, 4.0,2.0') goalListYaw = rospy.get_param('~goalListYaw', '0, 90.0,2.0') goals = [[float(x), float(y), float(yaw)] for (x, y, yaw) in zip(goalListX.split(","),goalListY.split(","),goalListYaw.split(","))] ##为了方便记忆,goals中[0]是终点,[1]到[8]分别对应场上的8个点,9是第一个框的识别点,10是第二个框的识别点,11是第三个框的识别点,12是第四个框的识别点 object_position = Object_position() ar_acker = ARTracker() executor_thread = threading.Thread(target=process).start() navi = Navigation() find_point_flag=[0,0,0,0] have_nav_flag=[0,0,0,0] time.sleep(10) navi.goto(goals[9]) find_point_flag[0]=1 while True: if find_id==1 or tag_id==1: both_id=1 elif find_id==2 or tag_id==2: both_id=2 elif find_id==3 or tag_id==3: both_id=3 elif find_id==4 or tag_id==4: both_id=4 elif find_id==5 or tag_id==5: both_id=5 elif find_id==6 or tag_id==6: both_id=6 elif find_id==7 or tag_id==7: both_id=7 elif find_id==8 or tag_id==8: both_id=8 else: both_id=0 if both_id==0: if have_nav_flag[0]==1 and find_point_flag[1]==0: navi.goto(goals[10]) find_point_flag[1]=1 if have_nav_flag[1]==1 and find_point_flag[2]==0: navi.goto(goals[11]) find_point_flag[2]=1 if have_nav_flag[2]==1 and find_point_flag[3]==0: navi.goto(goals[12]) find_point_flag[3]=1 if have_nav_flag[3]==1: navi.goto(goals[0]) break else: if both_id==1 and have_nav_flag[0]==0: navi.goto(goals[1]) have_nav_flag[0]=1 if both_id==2 and have_nav_flag[0]==0: navi.goto(goals[2]) have_nav_flag[0]=1 if both_id==3 and have_nav_flag[0]==0: navi.goto(goals[3]) have_nav_flag[1]=1 if both_id==4 and have_nav_flag[0]==0: navi.goto(goals[4]) have_nav_flag[1]=1 if both_id==5 and have_nav_flag[0]==0: navi.goto(goals[5]) have_nav_flag[3]=1 if both_id==6 and have_nav_flag[0]==0: navi.goto(goals[6]) have_nav_flag[3]=1 if both_id==7 and have_nav_flag[0]==0: navi.goto(goals[7]) have_nav_flag[4]=1 if both_id==8 and have_nav_flag[0]==0: navi.goto(goals[8]) have_nav_flag[4]=1
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LaoYuanPython

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值