Python中的时间转换函数是什么-创新互联
Python中的时间转换函数是什么?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
站在用户的角度思考问题,与客户深入沟通,找到涟水网站设计与涟水网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站建设、网站制作、企业官网、英文网站、手机端网站、网站推广、域名申请、网络空间、企业邮箱。业务覆盖涟水地区。一、字符串转时间戳
1、默认:
import time def time_str_to_timestamp(string_time, _format="%Y-%m-%d %H:%M:%S"): return int(time.mktime(time.strptime(string_time, _format)))
2、按时区转:
import time import datetime from pytz import timezone as tz def time_str_to_timestamp_by_timezone(string_time, _format="%Y-%m-%d %H:%M:%S”, from_tz=“UTC”, to_tz="America/Los_Angeles"): from_tz = tz(from_tz) to_tz = tz(to_tz) return int(time.mktime( datetime.datetime.strptime(string_time, _format).replace( tzinfo=from_tz).astimezone(to_tz).timetuple()))
二、时间戳转字符串
1、默认:
import time def timestamp_to_str(timestamp, _format="%Y-%m-%d %H:%M:%S"): return time.strftime(_format, time.localtime(timestamp))
2、按时区转:
import datetime from pytz import timezone as tz def timestamp_to_str_by_timezone(timestamp, _format="%Y-%m-%d %H:%M:%S”, to_tz="America/Los_Angeles"): to_tz = tz(to_tz) return str(datetime.datetime.fromtimestamp(timestamp, to_tz).strftime(_format))
三、字符串转datetime
1、默认:
import datetime def datetime_str_to_datetime(string_time, _format="%Y-%m-%d %H:%M:%S"): return datetime.datetime.strptime(string_time, _format)
2、按时区转:
import datetime from pytz import timezone as tz def datetime_str_to_datetime_by_timezone(string_time, from_tz=“UTC”, to_tz="America/Los_Angeles”, _format="%Y-%m-%d %H:%M:%S",): from_tz = tz(from_tz) to_tz = tz(to_tz) return datetime.datetime.strptime(string_time, _format).replace( tzinfo=from_tz).astimezone(to_tz)
四、datetime转字符串
1、默认:
import datetime def datetime_to_datetime_str(date, _format="%Y-%m-%d %H:%M:%S"): return date.strftime(_format)
2、按时区转:
import datetime from pytz import timezone as tz def datetime_to_datetime_str_by_timezone(date, from_tz=“UTC”, to_tz="America/Los_Angeles”, _format="%Y-%m-%d %H:%M:%S"): from_tz = tz(from_tz) to_tz = tz(to_tz) date = date.replace(tzinfo=from_tz).astimezone(to_tz) return date.strftime(_format)
五、datetime转时间戳
1、默认:
import time def datetime_to_timestamp(date): return int(time.mktime(date.timetuple()))
2、按时区转:
import time from pytz import timezone as tz def datetime_to_timestamp_by_timezone(date, from_tz=“UTC”, to_tz="America/Los_Angeles"): from_tz = tz(from_tz) to_tz = tz(to_tz) return int(time.mktime(date.replace( tzinfo=from_tz).astimezone(to_tz).timetuple()))
六、时间戳转datetime
1、默认:
import datetime def timestamp_to_datetime(time_stamp): return datetime.datetime.fromtimestamp(time_stamp)
2、按时区转:
import datetime from pytz import timezone as tz def timestamp_to_datetime_by_timezone(time_stamp, to_tz="America/Los_Angeles"): to_tz = tz(to_tz) return datetime.datetime.fromtimestamp(time_stamp, to_tz)
看完上述内容,你们掌握Python中的时间转换函数是什么的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
当前名称:Python中的时间转换函数是什么-创新互联
分享链接:http://ybzwz.com/article/gpecg.html