Python日期操作

1. 日期输出格式化

所有日期、时间的api都在datetime模块内。

1. datetime => string

  1. import datetime
  2. now = datetime.datetime.now()
  3. now.strftime('%Y-%m-%d %H:%M:%S')

2. string => datetime

  1. t_str = '2017-09-05 12:11:30'
  2. d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')

strptime是datetime类的静态方法。

3. 两个日期相差多少天。

  1. d1 = datetime.datetime.strptime('2016-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
  2. d2 = datetime.datetime.strptime('2016-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
  3. delta = d1 - d2
  4. print delta.days

输出:3

4. 今天的n天后的日期。

  1. now = datetime.datetime.now()
  2. delta = datetime.timedelta(days=3)
  3. n_days = now + delta
  4. print n_days.strftime('%Y-%m-%d %H:%M:%S')
Last modification:January 8th, 2019 at 09:33 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment