python 中 date与str转化及date之间的运算
目录
str相关运算
str转datetime
import datetime
str = "20180805"
str2date = datetime.datetime.strptime(str,"%Y%m%d") #字符串转化为date形式
date2str=str2date.strftime("%Y%m%d") #date形式转化为str
str = '2012-11-19'
date_time = datetime.datetime.strptime(str,'%Y-%m-%d') #注意str的格式要与'%Y-%m-%d'相匹配。
#因为import datetime,而 datetime下面还有一个 datetime,所以要引用它,就得用datetime.datetime
#如果用 from datetime import datetime, 就可以写成datetime.strptime(str,"%Y%m%d")
datetime转str
date_time = datetime.datetime(2012,11,19,0,0)
str = date_time.strftime('%Y-%m-%d')
#得到:'2012-11-19'
str转为timestamp (pandas里的日期时间数据格式)
settle_date = '2021-06-02'
pd.to_datetime(settle_date) 直接将字符格式的日期,转化为timestamps格式
datetime格式转为timestamps格式
date0 = datetime.strptime(settle_date, "%Y-%m-%d") #转为datetime格式
date0 = pd.Timestamp(date0) #datetime格式转为timestamps格式
#或者:把一列datetime型数字转为timestamp
date_col = pd.to_datetime(date_col)
timestamps转为datetime
month_list = pd.date_range('2020-01-01','2020-06-30',freq='M')
DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30',
'2020-05-31', '2020-06-30'],
dtype='datetime64[ns]', freq='M')
list(month_list)
Out:
[Timestamp('2020-01-31 00:00:00', freq='M'),
Timestamp('2020-02-29 00:00:00', freq='M'),
Timestamp('2020-03-31 00:00:00', freq='M'),
Timestamp('2020-04-30 00:00:00', freq='M'),
Timestamp('2020-05-31 00:00:00', freq='M'),
Timestamp('2020-06-30 00:00:00', freq='M')]
list(month_list.values)
Out:
[numpy.datetime64('2020-01-31T00:00:00.000000000'),
numpy.datetime64('2020-02-29T00:00:00.000000000'),
numpy.datetime64('2020-03-31T00:00:00.000000000'),
numpy.datetime64('2020-04-30T00:00:00.000000000'),
numpy.datetime64('2020-05-31T00:00:00.000000000'),
numpy.datetime64('2020-06-30T00:00:00.000000000')]
list(month_list)[0]
Out: Timestamp('2020-01-31 00:00:00', freq='M')
list(month_list.values)[0]
Out[: numpy.datetime64('2020-01-31T00:00:00.000000000')
list(month_list)[0].date()
Out: datetime.date(2020, 1, 31)
timestamp类型的特性
settle_date = '2021-06-02'
#方法一
date0 = datetime.strptime(settle_date, "%Y-%m-%d") #转为datetime格式
date0 = pd.Timestamp(date0) #datetime格式转为timestamps格式
#方法二
date0 = pd.to_datetime(settle_date) 直接将字符格式的日期,转化为timestamps格式
date0
Out: Timestamp('2021-06-02 00:00:00')
print(date0)
2021-06-02 00:00:00
dir(date0)
Out:
['asm8', 'astimezone', 'ceil', 'combine', 'ctime', 'date', 'day', 'day_name', 'day_of_week', 'day_of_year', 'dayofweek', 'dayofyear', 'days_in_month', 'daysinmonth', 'dst', 'floor',
'fold', 'freq', 'freqstr', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'is_leap_year', 'is_month_end', 'is_month_start', 'is_quarter_end', 'is_quarter_start',
'is_year_end', 'is_year_start', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'month_name', 'nanosecond', 'normalize', 'now', 'quarter',
'replace', 'resolution', 'round', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'to_datetime64', 'to_julian_date', 'to_numpy', 'to_period', 'to_pydatetime',
'today', 'toordinal', 'tz', 'tz_convert', 'tz_localize', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'value', 'week', 'weekday', 'weekofyear', 'year']
#其中常用的:
date0.date()
Out[0]: datetime.date(2021, 6, 2)
date0.day_name()
Out[1]: 'Wednesday'
date0.year
Out[2]: 2021
date0.month_name()
Out[3]: 'June'
date0.week
Out[4]: 22
date0.today()
Out[5]: Timestamp('2021-06-03 10:53:14.977925')
date0.to_datetime64()
Out[6]: numpy.datetime64('2021-06-02T00:00:00.000000000')
date0.isocalendar()
Out[7]: (2021, 22, 3)
date0.to_julian_date()
Out[8]: 2459367.5
date0.value
Out[9]: 1622592000000000000
date0.to_pydatetime()
Out[10]: datetime.datetime(2021, 6, 2, 0, 0)
date0.isoformat()
Out[11]: '2021-06-02T00:00:00'
date0.is_month_end
Out[12]: False
date0.is_leap_year
Out[11]: False
datetime运算
date与datetime互转
from datetime import datetime, date
# 获取datetime
now = datetime.now()
# 获取date
today = date.today()
# date 转 datetime
print('date 转 datetime:',datetime.combine(today, datetime.min.time()))
# datetime转date
print('datetime转date:',now.date())
date之间的运算
pre_date = date + datetime.datetime.timedelta(days=-1)
两个日期的计算
d1=datetime.datetime.strptime(starttime,"%Y%m%d")
d2=datetime.datetime.strptime(endtime,"%Y%m%d")
diff_days=d1-d2
print diff_days
有需要的直接?️复制下列代码
#!/usr/bin/env python
#-*-coding:utf-8
# author zhaoli
import datetime
import time
def str2date(str,date_format="%Y%m%d"):
date = datetime.datetime.strptime(str, date_format)
return date
def date2str(date,date_formate = "%Y%m%d"):
str = date.strftime(date_formate)
return str
def date_delta(date,gap,formate = "%Y%m%d"):
date = str2date(date)
pre_date = date + datetime.timedelta(days=-gap)
pre_str = date2str(pre_date,formate) # date形式转化为str
return pre_str
def str2timestamp(str,timestamp_len=10):
date_array = time.strptime(str,"%Y-%m-%d %H:%M:%S")
timestamp = int(time.mktime(date_array))
if timestamp_len==13:
timestamp *=1000
return timestamp