Python 时间格式转换

当前日期时间

from datetime import datetime

import time

dt=datetime.now()# 时间日期

ts=time.time()# 时间戳

st='2018-12-18 11:12:13'# 字符串

默认:

数值时间戳:时间戳是数值格式

时间字符串:字符串符合时间规范写法

时间日期:Python下的datetime.datetime类型

 

时间戳 <-> 字符串

字符串=datetime.fromtimestamp(时间戳).strftime(格式)

a_string=datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

时间戳=time.mktime(time.strptime(字符串,格式))

a_ts=time.mktime(time.strptime(st,'%Y-%m-%d %H:%M:%S'))

 

字符串 <-> 时间日期

时间日期=datetime.strptime(字符串,格式)

a_datetime=datetime.strptime(st,'%Y-%m-%d %H:%M:%S')

字符串=datetime.strftime(时间日期,格式)

a_string2=datetime.strftime(dt,'%Y-%m-%d %H:%M:%S')

 

时间戳 <-> 时间日期

时间日期=datetime.fromtimestamp(时间戳)

a_datetime2=datetime.fromtimestamp(ts)

时间戳=datetime.timestamp(时间日期)

a_ts2=datetime.timestamp(dt)

 

示例:

 

补充

DataFrame中一列统一处理_时间戳->时间日期

import pandas as pd

df['time'] = pd.to_datetime(df.timestamp, unit='s')

把这里的时间(time)转换成字符串

pd.Timestamp.strftime(df['time'][0], '%Y-%m-%d %H:%M:%S')

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值