# !!!! Python 2 datetime.datetime 对象没有timestamp方法!

在用Python处理datetime和timestamp的转换时发现在时区方面,Python的处理是个大坑。

因为Python的time是默认localtime输入来处理的,导致脚本在本地运行和在服务器运行会得到不一样的结果。一不注意就会中招。

R中也会碰到时区的问题,但是R的方法提供了tz选项来指定日期的时区,简化了问题。而Python 中的time.mktime无法对时区进行指定,带来了很多麻烦。查了很久,发现有一个time.timezone的属性,可以根据运行脚本的机器的时间,来灵活处理时区问题。

以下是datetime与timestamp转换的方法, 输入和输出都以GMT0为准.

 from datetime import datetime
import time def timestamp_datetime(ts):
if isinstance(ts, (int, float, str)):
try:
ts = int(ts)
except ValueError:
raise if len(str(ts)) == 13:
ts = int(ts / 1000)
if len(str(ts)) != 10:
raise ValueError
else:
raise ValueError() return datetime.fromtimestamp(ts) def datetime_timestamp(dt, type='ms'):
if isinstance(dt, str):
try:
if len(dt) == 10:
dt = datetime.strptime(dt.replace('/', '-'), '%Y-%m-%d')
elif len(dt) == 19:
dt = datetime.strptime(dt.replace('/', '-'), '%Y-%m-%d %H:%M:%S')
else:
raise ValueError()
except ValueError as e:
raise ValueError(
"{0} is not supported datetime format." \
"dt Format example: 'yyyy-mm-dd' or yyyy-mm-dd HH:MM:SS".format(dt)
) if isinstance(dt, time.struct_time):
dt = datetime.strptime(time.stftime('%Y-%m-%d %H:%M:%S', dt), '%Y-%m-%d %H:%M:%S') if isinstance(dt, datetime):
if type == 'ms':
ts = int(dt.timestamp()) * 1000
else:
ts = int(dt.timestamp())
else:
raise ValueError(
"dt type not supported. dt Format example: 'yyyy-mm-dd' or yyyy-mm-dd HH:MM:SS"
)
return ts if __name__ == '__main__':
try:
print(datetime_timestamp('2015-01-01 20:20:00', 's'))
print(timestamp_datetime(1420114800))
print(timestamp_datetime(1420114800123))
except Exception as e:
print(e.args[0])

  

Python datetime与timestamp之间的转换的更多相关文章

  1. python—时间与时间戳之间的转换

    python-时间与时间戳之间的转换 对于时间数据,如2016-05-05 20:28:54,有时需要与时间戳进行相互的运算,此时就需要对两种形式进行转换,在Python中,转换时需要用到time模块 ...

  2. Python数字与字符之间的转换

    Python数字与字符之间的转换 命令 意义 int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 co ...

  3. c# datetime与 timeStamp时间戳 互相转换

    将时间格式转化为一个int类型 // ::26时间转完后为:1389675686数字 为什么使用时间戳? 关于Unix时间戳,大概是这个意思,从1970年0时0分0秒开始到现在的秒数.使用它来获得的是 ...

  4. 常见的时间字符串与timestamp之间的转换 时间戳

    这里说的字符串不是一般意义上的字符串,是指在读取日期类型的数据时,如果还没有及时解析字符串,它就还不是日期类型,那么此时的字符串该怎么与时间戳之间进行转换呢? ① 时间字符串转化成时间戳 将时间字符串 ...

  5. python中进制之间的转换

    参考于:http://www.360doc.com/content/14/0428/11/16044571_372866302.shtml  在此非常感谢! ~~~~~~~~~~~~~~~~~~~~~ ...

  6. msyql DATETIME类型和Timestamp之间的转换

    DATETIME -> Timestamp: UNIX_TIMESTAMP(...) Timestamp -> DATETIME: FROM_UNIXTIME(...) select da ...

  7. python 时间与时间戳之间的转换

    https://blog.csdn.net/kl28978113/article/details/79271518 对于时间数据,如2016-05-05 20:28:54,有时需要与时间戳进行相互的运 ...

  8. String和Date、Timestamp之间的转换

    一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr = "2010/05/04 12:34:23&quo ...

  9. Java:String和Date、Timestamp之间的转换

    一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr = "2016-9-28 12:25:55" ...

随机推荐

  1. cf自训6

    cf946D 背包+区间dp 好题 /* 先预处理出每行消去i个1后可以的到的最小时间: 先求每行的前缀和,枚举左端点和右端点,消去的1 cost=tot-sum[r]+sum[l-1],区间长度=r ...

  2. Allegro PCB Design GXL (legacy) 由零散的对象构成一个Shape

    Allegro PCB Design GXL (legacy) version 16.6-2015 从DXF文件中导入板框之后,发现板框是由Line Segment.Arc Segment等对象组成, ...

  3. Linux系统下inode满了导致无法写文件的解决思路

    解决思路1:删除无用的临时文件,释放inode 进入/tmp目录,执行find -exec命令 find  /tmp  -type  f  -exec  rm  {}  \; 遍历寻找0字节的文件,并 ...

  4. windows 下命令行启动停止mysql

    MySQL比较好玩一点就是它可以用多种方式启动,当然它也可以用多种方式关闭.下面我就mysql的几种启动方式简单的谈一谈,希望可以给大家提供一些参考. 第一种,用mysqld-nt来启动. 在没有进行 ...

  5. IPMI无法执行命令

    IPMI无法执行命令 https://www.cnblogs.com/EricDing/p/8995263.html http://www.cnblogs.com/heidsoft/p/4014301 ...

  6. babelrc

    .babelrc文件 // 简单版 { "presets": ["es2015", "stage-2"], // 使用 es2015 npm ...

  7. 【loj6142】「2017 山东三轮集训 Day6」A 结论题+Lucas定理

    题解: 当奇数 发现答案就是C(n,1)^2+C(n,3)^2+...C(n,n)^2 倒序相加,发现就是C(2n,n) 所以答案就是C(2n,n)/2 当偶数 好像并不会证 打表出来可以得到 2.当 ...

  8. alpha冲刺6/10

    目录 摘要 团队部分 个人部分 摘要 队名:小白吃 组长博客:hjj 作业博客:感恩节~ 团队部分 后敬甲(组长) 过去两天完成了哪些任务 文字描述 设计了拍照界面和图片上传界面 沟通了前端进度 接下 ...

  9. 【Android】Tips for Android developer: “Conversion to Dalvik format failed: Unable to execute dex: null”

    Androiddeveloper, I have met a strange problem when I want use a third party jar, it remained me tha ...

  10. CentOS7下Django环境的搭建安装python3.6.5,virtualenv django1.11.14

    1.帖子1https://blog.csdn.net/a249900679/article/details/51527200 2.virtualenv https://www.cnblogs.com/ ...