时间处理

获取完整时间

  1. import pendulum
  2. import time
  3. # here put the import lib
  4. # 获取当前完整时间
  5. now = pendulum.now(tz="local")
  6. print(now) # 2022-05-31T15:41:12.163333+08:00

获取当前时间

  1. import pendulum
  2. # 获取当前时间
  3. print("to_time_string: ", pendulum.now(tz="local").to_time_string()) # to_time_string: 15:50:27
  4. print(pendulum.from_timestamp(timestamp, tz="local").time()) # 15:44:54.470152
  5. print("to_day_datetime_string: ", pendulum.now(tz="local").to_day_datetime_string()) # to_day_datetime_string: Tue, May 31, 2022 4:09 PM
  6. print("to_formatted_date_string: ", pendulum.now(tz="local").to_formatted_date_string()) # to_formatted_date_string: May 31, 2022
  7. """
  8. 获取当前时间和日期
  9. """
  10. # 2022-07-03 14:58:22
  11. pendulum.now().to_datetime_string()
  12. """获取当前日期"""
  13. # 2022-07-03
  14. pendulum.now().to_date_string()
  15. """获取当前时间"""
  16. # 14:58:22
  17. pendulum.now().to_time_string()

获取当前日期

  1. import pendulum
  2. import time
  3. # 获取当前日期
  4. print(pendulum.now(tz="local").date()) # 2022-05-31
  5. print("to_date_string: ", pendulum.now(tz="local").to_date_string()) # to_date_string: 2022-05-31
  6. timestamp = time.time()
  7. print(pendulum.from_timestamp(timestamp, tz="local").date()) # 2022-05-31

获取当前时区

  1. import pendulum
  2. # 获取当前时区
  3. print(pendulum.local_timezone()) # Timezone('Asia/Shanghai')

获取时间元组

  1. import pendulum
  2. # 获取时间元组
  3. res = pendulum.now().timetuple()
  4. print(res) # time.struct_time(tm_year=2022, tm_mon=5, tm_mday=31, tm_hour=15, tm_min=43, tm_sec=1, tm_wday=1, tm_yday=151, tm_isdst=0)
  5. print(res.tm_mday) # 31

时间运算

  1. """时间运算"""
  2. dt1 = pendulum.now()
  3. dt2 = pendulum.tomorrow()
  4. print(dt1, dt2)
  5. print(dt1.add(days=1)) # 输出时间 + 1天
  6. period = dt2 - dt1
  7. print("相隔多少年:", period.in_years()) # 相隔多少年: 0
  8. print("相隔多少月:", period.in_months())# 相隔多少月: 0
  9. print("相隔多少天:", period.in_days()) # 相隔多少天: 1
  10. print("相隔多少小时:", period.in_hours()) #相隔多少小时: 7
  11. print("相隔多少分钟:", period.in_minutes()) # 相隔多少分钟: 459
  12. print("相隔多少秒:", period.in_seconds()) # 相隔多少秒: 27543