Python时间格式转换全指南:字符串、时间戳与datetime互转及跨时区处理

清欢
清欢
发布时间:2026-10-13| 6人浏览过
原创

本文详细解析Python中字符串、时间戳与datetime对象之间的相互转换方法,重点涵盖默认时区与跨时区转换的实现。通过提供完整的代码示例,帮助开发者解决海外业务中常见的时区转换难题,掌握高效的时间处理技巧。

Python时间转换函数详解

本文详细介绍Python中时间转换函数的具体用法,旨在为读者提供实用的参考案例。

前言

Python时间格式转换概述

Python支持多种时间格式,格式间的转换是开发中常见且易混淆的环节。与PHP不同,Python并未将时间字符串与datetime模块紧密绑定,无法仅靠单一函数完成双向转换。尽管网上已有相关教程,但鉴于海外业务对多时区转换的频繁需求,本文将重点总结按时区进行各类时间格式转换的方法。

转换方法图示(图片转自网络):

字符串与时间戳互转

一、字符串转时间戳

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互转

三、字符串转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与字符串互转

四、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与时间戳互转

五、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互转

六、时间戳转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)

在线日期计算工具推荐

PS:这里再为大家推荐几款关于日期与天数计算的在线工具供大家使用:

在线日期/天数计算器: http://tools.jb51.net/jisuanqi/date_jisuanqi

在线万年历日历: http://tools.jb51.net/bianmin/wannianli

在线阴历/阳历转换工具: http://tools.jb51.net/bianmin/yinli2yangli

Unix时间戳(timestamp)转换工具: http://tools.jb51.net/code/unixtime

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python日期与时间操作技巧总结》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。