Wonderjar's Blog

python2.7日期操作

2019-03-04

python2.7里的日期处理

string > datetime

1
str.strftime("%Y-%m-%d %H:%M:%S")

datetime > string

1
2
import datetime
datetime.datetime.strptime(str_val, "%Y-%m-%d %H:%M:%S")

将无时区时间转为有时区,例子

1
2
3
4
import datetime
import pytz
dt = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
dt = (dt - datetime.timedelta(hours=8)).replace(tzinfo=pytz.timezone('UTC'))
1
2
3
4
5
# 虽然这样可以指定特定地区,但没有Asia/Beijing,而Asia/Shanghai与UTC时间相差其实是+8:06:00 
import pytz
from datetime import datetime
now = datetime.now()
now = now.replace(tzinfo=pytz.timezone('Asia/Shanghai'))

清除时分秒

1
2
import datetime
datetime.datetime.now().replace(hour=0,minute=0,second=0,microsecond=0)
Tags: Python