欢迎访问宙启技术站
智能推送

Python时间和日期函数的使用方法及格式化输出技巧

发布时间:2023-07-06 01:04:28

Python中有很多内置的模块可以用于处理时间和日期,其中最常用的是datetime模块。datetime模块提供了很多函数和类用于处理时间和日期,下面是一些使用方法和格式化输出的技巧。

1. 导入datetime模块:

   import datetime
   

2. 获取当前时间和日期:

   now = datetime.datetime.now()
   print(now)
   

输出结果:

   2021-09-22 11:30:00.123456
   

3. 格式化时间和日期:

   now = datetime.datetime.now()
   formatted = now.strftime("%Y-%m-%d %H:%M:%S")
   print(formatted)
   

输出结果:

   2021-09-22 11:30:00
   

在格式字符串中,%Y表示4位数的年份,%m表示2位数的月份,%d表示2位数的日期,%H表示24小时制的小时数,%M表示分钟数,%S表示秒数。

4. 解析字符串为时间和日期:

   formatted = "2021-09-22 11:30:00"
   parsed = datetime.datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S")
   print(parsed)
   

输出结果:

   2021-09-22 11:30:00
   

5. 获取特定时间和日期的差值:

   past = datetime.datetime(2021, 9, 1)
   now = datetime.datetime.now()
   diff = now - past
   print(diff.days)
   

输出结果:

   21
   

days属性表示两个日期之间的天数差值。

6. 在时间和日期上进行加减运算:

   now = datetime.datetime.now()
   future = now + datetime.timedelta(days=7)
   print(future)
   

输出结果:

   2021-09-29 11:30:00.123456
   

timedelta表示时间和日期的差值,可以通过参数指定要加减的天数、小时数、分钟数、秒数等。

7. 获取时间和日期的各个部分:

   now = datetime.datetime.now()
   year = now.year
   month = now.month
   day = now.day
   hour = now.hour
   minute = now.minute
   second = now.second
   microsecond = now.microsecond
   print(year, month, day, hour, minute, second, microsecond)
   

输出结果:

   2021 9 22 11 30 0 123456
   

以上是一些常见的Python时间和日期函数的使用方法和格式化输出技巧。除了datetime模块外,还有其他一些模块如timecalendar也可以用于处理时间和日期。根据具体的需求,选择合适的模块和函数来处理时间和日期。