基础知识见:

datetime

注意timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的。

timestamp的值与时区毫无关系,因为timestamp一旦确定,其UTC时间就确定了,转换到任意时区的时间也是完全确定的,这就是为什么计算机存储的当前时间是以timestamp表示的,因为全球各地的计算机在任意时刻的timestamp都是完全相同的(假定时间已校准)。

# 拿到UTC时间,并强制设置时区为UTC+0:00:
utc_d = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_d)
# astimezone()将转换时区为北京时间:
utc_dt = utc_d.astimezone(timezone(timedelta(hours=8)))
print(utc_dt)
# 东8区,也就是北京的时间戳
print(utc_dt.timestamp())
# astimezone()将转换时区为东京时间:
utc_dt = utc_d.astimezone(timezone(timedelta(hours=9)))
print(utc_dt)
# 东9区,也就是东的时间戳
print(utc_dt.timestamp())

结果:

2017-07-27 16:28:19.287400+00:00
2017-07-28 00:28:19.287400+08:00
1501172899.2874
2017-07-28 01:28:19.287400+09:00
1501172899.2874

由此看出,北京和东京差一个时区,东京早北京一个小时,但同一时刻的时间戳是一样的

实践学习

假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:

  • 第一种形式
import re
from datetime import datetime, timezone, timedeltadef to_timestamp(dt_str, tz_str):    # dt_str转换为datetime格式dt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')print('To datetime:',dt)# tz_str转换为timezone,用?表示0个或1个字符m = re.match(r'^(UTC)([+-]?)([0-9]|0[0-9]|1[0-2]):(00)$', tz_str)print('get the timezone:',m.group(3))sign = -1 if m.group(2) is '-' else 1#print(sign)tz = sign * int(m.group(3))#  创建时区tz_utc = timezone(timedelta(hours=tz))# 时间转换为UTC时间dt_utc = dt.replace(tzinfo=tz_utc)print('datetime of UTC:',dt_utc)    # datetime转换为timestampreturn dt_utc.timestamp()t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
print('the timestamp of t1:',t1)
print('...............................................')t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
print('the timestamp of t2:',t2)print('end')

运行结果:

To datetime: 2015-06-01 08:10:30
get the timezone: 7
datetime of UTC: 2015-06-01 08:10:30+07:00
the timestamp of t1: 1433121030.0
...............................................
To datetime: 2015-05-31 16:10:30
get the timezone: 09
datetime of UTC: 2015-05-31 16:10:30-09:00
the timestamp of t2: 1433121030.0
end
  • 第二种形式
def to_timestamp(dt_str, tz_str):# dt_str转换为datetimedt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')# 主要是正则表达式的不同,很强大!UTC=int(re.match(r'^UTC([-+]*\d{1,2}):00$',tz_str).group(1))tz_utc=timezone(timedelta(hours=UTC))lastdt=dt.replace(tzinfo=tz_utc)timestamp=lastdt.timestamp()return timestamp
t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
print('the timestamp of t1:',t1)
print('...............................................')
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
print('the timestamp of t2:',t2)
print('end')

结果:

>>>
the timestamp of t1: 1433121030.0
...............................................
the timestamp of t2: 1433121030.0
end
>>> 
  • 第三种形式
def to_timestamp(dt_str, tz_str):dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')# 采用分割,也是正则表达式的不同tz_info = re.split(r'[UTC\:]+',tz_str)print(tz_info)tz_hours = int(tz_info[1])tz_minutes = int(tz_info[2])# 细分到分钟dt = dt.replace(tzinfo = timezone(timedelta(hours=tz_hours, minutes=tz_minutes)))return dt.timestamp()t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
print('the timestamp of t1:',t1)
print('...............................................')
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
print('the timestamp of t2:',t2)
print('end')

结果:

>>>
['', '+7', '00']
the timestamp of t1: 1433121030.0
...............................................
['', '-09', '00']
the timestamp of t2: 1433121030.0
end
>>>

python的datetime模块相关推荐

  1. python中datetime模块常用方法_Python中datetime的使用和常用时间处理

    datetime在python中比较常用,主要用来处理时间日期,使用前先倒入datetime模块.下面总结下本人想到的几个常用功能. 1.当前时间: >>> print dateti ...

  2. python的datetime模块需要装吗,Python datetime模块的介绍(日期格式化 时间戳)

    datetime模块常用的主要有下面这四个类:(要清楚import datetime : 导入的是datetime这个包,包里有各种类) 1. datetime.date   用于表示年月日构成的日期 ...

  3. python中datetime模块_python中的datetime模块

    datetime是python中日期和时间管理模块,包含date,time,datetime,timedelta,datetime_CAPI,sys,timezone等类 datetime模块中包含的 ...

  4. python之datetime模块

    目录 time模块和datetime模块的关系 time模块 datetime模块 日期和时间数据类型 数据类型 datetime参数 字符串转换 格式说明 dateutil NaT 时间序列基础 日 ...

  5. python的datetime模块用法_Python3.5内置模块之time与datetime模块用法实例分析

    本文实例讲述了python3.5内置模块之time与datetime模块用法.分享给大家供大家参考,具体如下: 1.模块的分类 a.标准库(python自带):sys.os模块 b.开源模块(第三方模 ...

  6. python利用datetime模块计算时间差

    python中通过datetime模块可以很方便的计算两个时间的差,datetime的时间差单位可以是天.小时.秒,甚至是微秒,下面我们就来详细看下datetime的强大功能吧 今天写了点东西,要计算 ...

  7. python 的datetime模块使用

    1.datetime模块主要是5个类 date #日期类 年月日 datetime.date(year,month,day) time #时间类 时分秒 datetime.time(hour,minu ...

  8. 【python】datetime模块计算时间差

    一.问题背景 最近有小伙伴反馈接口平台的测试计划执行耗时显示有误,比如执行实际时长超过10s,但是报告中显示总耗时小于1s 显示耗时统计出现问题 二.问题排查 开始和结束时间是否有误 开始时间: 20 ...

  9. python中datetime模块是以什么时间为基础_Python基础之datetime模块

    Outline 构建时间对象实例 date实例的构造 time实例的构造 datetime实例的构造 timedelta对象的构造 tzinfo介绍 时间转换 时间对象转字符串 字符串转时间对象 时间 ...

最新文章

  1. Android Studio调试功能使用总结
  2. Linux的关机与重启命令
  3. 剑指Offer - 面试题4. 二维数组中的查找(双指针)
  4. iap php,PHP语言之华为应用内支付IAP验签
  5. preg_replace在java中_Java相当于PHP的preg_replace_callback
  6. pythonm 用法-------list实现购物车
  7. 用segnet训练我自己的数据,实验笔记1——改变图片大小
  8. 深度学习2.0-28.其他训练tricks-Early Stopping,dropout等
  9. Web应用启动时,后台自动启动一个线程
  10. aaa logo汉子字体_AAA Logo –标志设计软件
  11. Python爬虫(四)——小说下载器
  12. Ubuntu 16.04安装sogou 拼音输入法
  13. JAVA中如何解决超卖,Redis解决库存超卖问题实例讲解
  14. 开机provision应用
  15. HTML5期末大作业:出行网站设计——西安旅游-高质量(9页) HTML+CSS+JavaScript 学生DW网页设计
  16. 元胞自动机模拟森林火灾--matlab实现
  17. 电脑不能连接wifi怎么办连不上wifi怎么办
  18. 「Git」常用工作流介绍
  19. SpringBoot+Vue项目毕业论文管理系统
  20. 逾20万人“云围观”,第八届全球云计算大会乘风破浪而来

热门文章

  1. C语言求网格的最大不重复路径数的算法(附完整源码)
  2. c++运算符和结合性
  3. 返回图片_Vue 图片压缩并上传至服务器
  4. Cifar10与ResNet18实战、lenet5、resnet(学习笔记)
  5. 04_Flink-HA高可用、Standalone集群模式、Flink-Standalone集群重要参数详解、集群节点重启及扩容、启动组件、Flink on Yarn、启动命令等
  6. 本地编译Hadoop2.8.0源码总结和问题解决(转自:http://blog.csdn.net/young_kim1/article/details/50324345)
  7. webview与js交互
  8. 1QPushButton的使用,QLineEdit的使用,设置组件位置,布局(QHBoxLayout,QGridLayout)
  9. 通过sqlplus执行*.sql文件时常见的问题总结
  10. YOLOv3 学习笔记:大神好贴汇总+自身经验记录