Python时间转换:从三种时间格式到统一格式

作者:半吊子全栈工匠2024.02.23 13:47浏览量:35

简介:本文将介绍Python中三种常见的时间格式(字符串、datetime对象和时间戳),以及如何将它们转换为统一的格式以便进行比较和处理。

在Python中,时间可以以多种格式存在,最常见的有字符串、datetime对象和时间戳。为了方便处理和比较,通常需要将它们转换为统一的格式。下面我们将介绍如何进行这三种时间格式的转换。

  1. 字符串到datetime对象

Python中的datetime模块提供了将字符串转换为datetime对象的方法。我们可以使用strptime函数,该函数接受两个参数:要解析的字符串和日期时间的格式。

  1. from datetime import datetime
  2. date_string = '2023-07-19 15:30:00'
  3. date_format = '%Y-%m-%d %H:%M:%S'
  4. date_object = datetime.strptime(date_string, date_format)
  5. print(date_object)
  1. datetime对象到字符串

要将datetime对象转换为字符串,我们可以使用strftime函数,该函数接受一个参数:日期时间的格式。

  1. from datetime import datetime
  2. date_object = datetime(2023, 7, 19, 15, 30, 0)
  3. date_string = date_object.strftime('%Y-%m-%d %H:%M:%S')
  4. print(date_string)
  1. datetime对象到时间戳

时间戳是从1970年1月1日00:00:00开始经过的秒数。我们可以使用timestamp属性将datetime对象转换为时间戳。

  1. from datetime import datetime
  2. date_object = datetime(2023, 7, 19, 15, 30, 0)
  3. timestamp = date_object.timestamp()
  4. print(timestamp)
  1. 时间戳到datetime对象

要将时间戳转换为datetime对象,我们可以使用fromtimestamp函数。这个函数接受一个参数:时间戳。

  1. from datetime import datetime
  2. timestamp = 1679546400 # 假设这是某个时间的时间戳(实际值可能不同)
  3. date_object = datetime.fromtimestamp(timestamp)
  4. print(date_object)
  1. 时间戳到字符串(以特定格式)

要将时间戳转换为字符串,我们需要先将其转换为datetime对象,然后使用strftime函数将其格式化为所需的字符串格式。

  1. from datetime import datetime
  2. timestamp = 1679546400 # 假设这是某个时间的时间戳(实际值可能不同)
  3. date_object = datetime.fromtimestamp(timestamp)
  4. date_string = date_object.strftime('%Y-%m-%d %H:%M:%S') # 将日期时间格式化为字符串形式 '2023-07-19 15:30:00' 等同于 '2023-07-19T15:30:00Z' 的ISO 8601格式。
  5. print(date_string)