python处理时间

  1. 将时间字符串转换为datetime对象:
import datetime
time_string = "2022-01-01 10:30:00"
datetime_obj = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
  1. 将datetime对象转换为时间字符串:
import datetime
datetime_obj = datetime.datetime(2022, 1, 1, 10, 30, 0)
time_string = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
  1. 将时间字符串转换为unix时间戳:
import datetime
time_string = "2022-01-01 10:30:00"
datetime_obj = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
unix_timestamp = datetime_obj.timestamp()
  1. 将unix时间戳转换为datetime对象:
import datetime
unix_timestamp = 1641029400
datetime_obj = datetime.datetime.fromtimestamp(unix_timestamp)
  1. 获取当前的时间字符串:
import datetime
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1. 获取当前的unix时间戳:
import time
current_unix_timestamp = time.time()
  1. 在时间上进行加减操作:
import datetime
datetime_obj = datetime.datetime.now()
new_datetime_obj = datetime_obj + datetime.timedelta(days=2, hours=3)
  1. 比较两个时间的大小:
import datetime
time1 = datetime.datetime(2022, 1, 1)
time2 = datetime.datetime(2022, 2, 1)
if time1 < time2:
    print("time1 is earlier than time2")
  1. 获取特定格式的当前时间:
import time
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  1. 将时间字符串转换为特定时区的datetime对象:
import datetime
import pytz
time_string = "2022-01-01 10:30:00"
timezone = pytz.timezone("Asia/Shanghai")
datetime_obj = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S").astimezone(timezone)

已发布

分类

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注