时区
- 北京时间与世界标准时间(UTC) 差别 (英語:Coordinated Universal Time,法語:Temps Universel Coordonné,简称UTC),快8个小时。
In [31]: datetime.datetime.utcfromtimestamp(1172969203)
Out[31]: datetime.datetime(2007, 3, 4, 0, 46, 43)
In [32]: datetime.datetime.fromtimestamp(1172969203)
Out[32]: datetime.datetime(2007, 3, 4, 8, 46, 43)
In [33]: datetime.datetime.utcnow()
Out[33]: datetime.datetime(2020, 10, 10, 2, 32, 30, 75856)
In [34]: datetime.datetime.now()
Out[34]: datetime.datetime(2020, 10, 10, 10, 32, 32, 632855)
- 当前的时间戳 timestamp: time.time(). 返回格式:1602297835.24672。
- time.time()表示在北京时间下,当前时间与 '1970-01-01 08:00:00'(等于time.localtime(0))相差秒数。
time 模块
def get_day(nday,fmt,bizdate=None):
import time
t = time.time() if bizdate is None else time.mktime(time.strptime(bizdate, fmt))
return time.strftime(fmt, time.localtime(t+nday*24*3600)) # time.gmtime
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time()) )
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()) )
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # ==
python datetime模块
- 获取时间差
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now()
print (endtime - starttime).seconds
- 相对时间,与字符串互转
lastday =(datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
datetime.datetime.strptime('2015-02-01','%Y-%m-%d')
R
today = Sys.Date()
beginday = seq(today, length.out=2, by="-40 day")[2]
beginday = format(beginday, '%Y%m%d')
dt1 = as.Date(as.character(dat1$date), '%Y%m%d')
dt2 = as.Date('20150101', '%Y%m%d')
flag_ = dt1 - dt2 >=-14 & dt1 - dt2 <= 0
在R中查看代码运行时间,用system.time
linux
OPTARG = '-1 day'
date_str=$(date -d "$OPTARG" '+%Y%%%m%%%d%%')
MAC OS X
date_str=$(date -v-1d '+%Y%%%m%%%d%%')
其他
pandas 日期转化为秒, 算时间差. 注意有时区差, 第一个方法非常高效
df.time = pd.to_datetime(df.time, format='%Y%m%d').astype(int) // int(1e9)
df.time = df.time.map(lambda dt: int(time.mktime(datetime.strptime(str(dt), "%Y%m%d").timetuple())))