您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。