您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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中的时间转换函数是什么的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。