1. 程式人生 > >Python datetime模組使用

Python datetime模組使用

Python的time 模組功能有限,計算日期的加減的時還是用datetime比較方便

首先 import datetime
當然也可以
from datetime import datetime
from datetime import timedelta
的方式引入

以下程式碼均是在linux python 命令列輸入顯示:
一、string轉datetime

str = ‘2012-11-19’

date_time = datetime.datetime.strptime(str,’%Y-%m-%d’)

date_time

datetime.datetime(2012,11,19,0,0)

二、datetime轉string

date_time.strftime(‘%Y-%m-%d’)

‘2012-11-19’

三、時間的加減
1 . 計算date_time的後一天

date_time + datetime.timedelta(days=1)
datetime.datetime(2012, 11, 20, 0, 0)

2 . 計算date_time的前一天

date_time + datetime.timedelta(days=-1)
datetime.datetime(2012, 11, 18, 0, 0)

3 .計算date_time 的前一個小時

date_time + datetime.timedelta(hours=1)
datetime.datetime(2012, 11, 19, 1, 0)

本來以為timedelta 還可以直接計算 months和 years的,卻發現報錯:

>>> date_time + datetime.timedelta(months=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'months' is an invalid keyword argument for
this function

class datetime.timedelta([days[, seconds[, microseconds[,
[, minutes[, hours[, weeks]]]]]]]) All arguments are
optional and default to 0. Arguments may be ints, longs, or floats,
and may be positive or negative.

Only days, seconds and microseconds are stored internally. Arguments
are converted to those units:

A millisecond is converted to 1000 microseconds. A minute is converted
to 60 seconds. An hour is converted to 3600 seconds. A week is
converted to 7 days.