20 Apr 2009

Python Tips - 日期字符串格式化

Python中的datetime和time模块用来处理日期格式,具体实现请看示例:

Using datetime and time modules in Python:



>>> import time
>>> t1 = time.localtime()
>>> t1
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=20, tm_hour=20, tm_min=8, tm_sec=47, tm_wday=0, tm_yday=110, tm_isdst=1)
>>> strFormat = "%Y-%m-%d %H:%M:%S"
>>> t2 = time.strftime(strFormat)
>>> t2
'2009-04-20 20:09:29'


所有格式化字符串意义如下:

All format strings are listed as following:
%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


再附上一个网友收藏的日期处理及格式例子:

Another example from the internet:
#!/usr/bin/python
#coding:utf-8
import datetime
import time

format="%Y-%m-%d %H:%M:%S"
t1=time.strptime("2008-01-31 00:11:23",format)
t2=datetime.datetime(t1[0],t1[1],t1[2],t1[3],t1[4],t1[5],t1[6])
t3=t2-datetime.timedelta(minutes=30)
t3=str(t3)

b1=t3[0:4]
b2=t3[5:7]
b3=t3[8:10]
b4=t3[11:13]
b5=t3[14:16]
b6=t3[-2:]

print b1
print b2
print b3
print b4
print b5
print b6


另一种 时间格式化方法 xiaoyu9805119 提供

datetime formats method from xiaoyu9805119
a="2009-02-15 21:00:08"
import re
s=re.split("\D*",a)
print s


另一种 时间加减方法 3227049提供

datetime computes method from 3227049
import datetime,time
format="%Y-%m-%d %H:%M:%S"
result=datetime.datetime(*time.strptime("2008-01-31 00:11:23",format)[:6])-datetime.timedelta(minutes=30)
print result.strftime(format)

No comments :

Post a Comment