Python DateTime 时间日期处理.

DateTime

获取当前 DateTime

1
2
from datetime timport datetime
datetime.datetime.now()

获取当天 date

1
datetime.date.today()

获取明天/前N天

1
2
3
4
5
# 明天
atetime.date.today() + datetime.timedelta(days=1)
# 前N天
datetime.datetime.now()
datetime.datetime.now() - datetime.timedelta(days=3)

获取当天开始和结束时间

1
2
datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime.combine(datetime.date.today(), datetime.time.max)

获取两个 datetime 的时间差

1
2
3
4
now = datetime.now()
end = datetime.strptime('2018-10-25 22:00','%Y-%m-%d %H:%M')
time = end - now
print(time.days,'天')

获取本周/本月/上月最后一天

  • 本周最后一天
1
2
3
4
import datetime
today = datetime.date.today()
sunday = today + datetime.timedelta(6 - today.weekday())
sunday
  • 本月最后一天
1
2
3
4
5
import calendar
today = datetime.date.today()
last_day_num = calendar.monthrange(today.year, today.month)
last_day = datetime.date(today.year, today.month, last_day_num)
last_day
  • 上月最后一天
1
2
3
4
import datetime
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
lastMonth = first - datetime.timedelta(days=1)

转换

datetime <=> string

  • datetime -> string
1
2
import datetime
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  • string -> datetime
1
2
import datetime
datetime.datetime.strptime("2018-10-22 12:50:46", "%Y-%m-%d %H:%M:%S")

datetime <=> timetuple

  • datetime -> timetuple
1
2
import datetime
datetime.datetime.now().timetuple()
  • timetuple -> datetime
1
timetuple => timestamp => datetime [看后面datetime<=>timestamp]

datetime <=> date

  • datetime -> date
1
2
import datetime
datetime.datetime.now().date()
  • date -> datetime
1
2
3
4
datetime.date.today()
today = datetime.date.today()
datetime.datetime.combine(today, datetime.time())
datetime.datetime.combine(today, datetime.time.min)

datetime <=> timestamp

  • datetime -> timestamp
1
2
3
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())
timestamp

timestamp -> datetime

1
datetime.datetime.fromtimestamp(1421077403.0)

Via


本站由 VITAN 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。