工作中遇到了很多需要時間轉換的時候,記錄一下,也不用每次都查看啦
1.日期格式化
我用time模塊比較多,也可以使用datetime.datetime模塊
1)str轉date型
time.strptime(date_str, format)
2)date型轉str
time.strftime(format, date_tuple)
3)timestamp轉date
datetime.datetime.fromtimestamp(int(timestamp)).strftime(time_format)
4)date轉timestamp
int(time.mktime(datetime.datetime.strptime(date, time_format).timetuple()))
2.日期加減
在datetime模塊中有timedelta類,這個類的對象用於表示一個時間間隔,比如兩個日期或者時間的差別,也可以用於直接計算日期時間的加減。
1)兩個日期相差多少天
day1 = datetime.datetime.strptime('2016-03-29', '%Y-%m-%d') day2 = datetime.datetime.strptime('2016-03-25', '%Y-%m-%d') delta = day1 - day2 print delta.days
2)某一個時間的第N天
s_t = datetime.datetime.strptime(sometime_str, time_format)
s_t = s_t + datetime.timedelta(days=day_add)
3.關於format參數
%a Abbreviated weekday name
%A Full weekday name
%b Abbreviated month name
%B Full month name
%c Date and time representation appropriate for locale
%d Day of month as decimal number (01 - 31)
%H Hour in 24-hour format (00 - 23)
%I Hour in 12-hour format (01 - 12)
%j Day of year as decimal number (001 - 366)
%m Month as decimal number (01 - 12)
%M Minute as decimal number (00 - 59)
%p Current locale's A.M./P.M. indicator for 12-hour clock
%S Second as decimal number (00 - 59)
%U Week of year as decimal number, with Sunday as first day of week (00 - 51)
%w Weekday as decimal number (0 - 6; Sunday is 0)
%W Week of year as decimal number, with Monday as first day of week (00 - 51)
%x Date representation for current locale
%X Time representation for current locale
%y Year without century, as decimal number (00 - 99)
%Y Year with century, as decimal number
%z, %Z Time-zone name or abbreviation; no characters if time zone is unknown
%% Percent sign