python时间戳与日期格式互转

来源:互联网 发布:阿里云服务器安全配置 编辑:程序博客网 时间:2024/05/17 08:33
def stamp_to_datetime(stamp,strformat="%Y-%m-%d %H:%M:%S"):
"""时间戳转日期格式"""import datetimeimport timestamp = int(stamp)strf = time.strftime(strformat,time.localtime(stamp))dt_format = datetime.datetime.strptime(strf,strformat)return dt_format

或者

def stamp_to_time(stamp,strformat="%Y-%m-%d %H:%M:%S"):stamp = int(stamp)ltime = time.localtime(stamp)timeStr = time.strftime(strformat, ltime)return timeStr

日期格式转时间戳

def datetime_toTimestamp(date_time):return int(time.mktime(date_time.timetuple()))
如:print datetime_toTimestamp(datetime.datetime.now())


把时间格式字符串转成时间格式

def string_toDatetime(string,strformat='%Y-%m-%d %H:%M:%S'):return datetime.datetime.strptime(string, strformat)#如:print string_toDatetime("2016-10 10:10:10")

把时间格式字符串转时间戳
def string_toTimestamp(strTime,strformat='%Y-%m-%d %H:%M:%S'):    date_format = datetime.datetime.strptime(strTime, strformat)    return int(time.mktime(date_format.timetuple()))

#如:
string_toTimestamp('2016-10 10:10:10')


计算前后日期、时间

def get_last_time(date,n_day=0,n_hour=0,n_min=0,n_sec=0,fm="%Y-%m-%d %H:%M:%S"):    """    获取上一个/下一个日期、小时、分、秒       正数为上一个,负数为下一个    返回字符串日期格式    """    now_date = datetime.datetime.strptime(date,fm)    last_date = now_date - datetime.timedelta(days=n_day,hours=n_hour,minutes=n_min,seconds=n_sec)    last_date_str = last_date.strftime(fm)    return last_date_str print get_last_time('2017-03-06 02:00:01')



0 0
原创粉丝点击