获取当前日期和时间
获取指定日期和时间
datetime转换为timestamp dt.datestamp()
在计算机中,时间实际上是用数字表示的。我们把1970年1月1日 00:00:00 UTC+00:00时区的时刻称为epoch time,记为0
(1970年以前的时间timestamp为负数),当前时间就是相对于epoch time的秒数,称为timestamp。
from datetime import datetime dt=datetime(2015,4,19,12,20) dt.timestamp() 1429417200.
timestamp转换为datetime datetime.fromtimestamp()
str转换为datetime datetime.strptime()
from datetime import datetime cday=datetime.strptime('2015-6-1 18:19:59','%Y-%m-%d %H:%M:%S') print(cday) 2015-06-01 18:19:59
datetime转换为str strftime()
datetime加减 time +/- timedelta(days= ,hours= ,minites= )
本地时间转换为UTC时间
时区转换
utc_dt=datetime.utcnow().replace(tzinfo=timezone.utc) bj_dt=utc_dt.astimezone(timezone(timedelta(hours=8))) #转换位北京时间
import re from datetime import datetime, timezone, timedelta def to_timestamp(dt_str, tz_str): ctime=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') utchour=int(re.match(r'UTC(-0[0-9]|-[0-9]|+0[0-9]|+[0-9]):00',tz_str).group(1)) tz_utc=timezone(timedelta(hours=utchour)) utctime=ctime.replace(tzinfo=tz_utc) return utctime.timestamp()