参考网址,写的很棒:

http://www.open-open.com/lib/view/open1479363382807.html

个人封装好的函数,可以互相转换

class my_datetime():
"""
Basic usage: a = datetime.datetime(2016, 9, 21, 13, 42, 8)
b = "2016-11-15 15:32:12"
c = u'2016-09-21 13:37:34'
print type(c)
d = 1474436826.0
e = 13710788676.0
ret = my_datetime()
res = ret.become_datetime(e)
print res
print type(res)
""" def __init__(self):
# 缺少对utc时间的判断
pass def become_timestamp(self, dtdt):
# 将时间类型转换成时间戳
if isinstance(dtdt, datetime.datetime):
timestamp = time.mktime(dtdt.timetuple())
return timestamp elif isinstance(dtdt, str):
if dtdt.split(" ")[1:]:
a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(a_datetime.timetuple())
else:
a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d")
timestamp = time.mktime(a_datetime.timetuple())
return timestamp elif isinstance(dtdt, float):
return dtdt # elif isinstance(dtdt, unicode):
# if dtdt.split(" ")[1:]:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
# timestamp = time.mktime(a_datetime.timetuple())
# else:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d")
# timestamp = time.mktime(a_datetime.timetuple())
# return timestamp def become_datetime(self, dtdt):
# 将时间类型转换成datetime类型
if isinstance(dtdt, datetime.datetime):
return dtdt elif isinstance(dtdt, str):
if dtdt.split(" ")[1:]:
a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
else:
a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d")
return a_datetime elif isinstance(dtdt, float):
# 把时间戳转换成datetime类型
a_datetime = datetime.datetime.fromtimestamp(dtdt)
return a_datetime # elif isinstance(dtdt, unicode):
# if dtdt.split(" ")[1:]:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
# else:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d")
# return a_datetime def become_str(self, dtdt):
# 把时间类型转换成字符串
if isinstance(dtdt, datetime.datetime):
a_datetime = dtdt.strftime("%Y-%m-%d %H:%M:%S")
return a_datetime elif isinstance(dtdt, str):
return dtdt elif isinstance(dtdt, float):
a_datetime_local = datetime.datetime.fromtimestamp(dtdt)
a_datetime = a_datetime_local.strftime("%Y-%m-%d %H:%M:%S")
return a_datetime # elif isinstance(dtdt, unicode):
# # 区别:一个是strp, 一个是strf
# if dtdt.split(" ")[1:]:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d %H:%M:%S")
# a_datetime = a_datetime.strftime("%Y-%m-%d %H:%M:%S")
# else:
# a_datetime = datetime.datetime.strptime(dtdt, "%Y-%m-%d")
# a_datetime = a_datetime.strftime("%Y-%m-%d")
# return a_datetime @staticmethod
def str_datetime():
return (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")

time模块

time模块提供各种操作时间的函数

说明:一般有两种表示时间的方式:
       1.时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的

2.以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同

The tuple items are:
year (including century, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
   time()  -- 返回时间戳
sleep() -- 延迟运行单位为s
gmtime() -- 转换时间戳为时间元组(时间元组)
localtime() -- 转换时间戳为本地时间对象
asctime() -- 将时间对象转换为字符串
ctime() -- 将使劲按戳转换为字符串
mktime() -- 将本地时间转换为时间戳
strftime() -- 将时间对象转换为规范性字符串

常用的格式代码:

     %Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
striptime() --将时间字符串根据指定的格式化字符转换成数组形式的时间 print(time.time()) ---返回当前时间戳
print(time.ctime()) ---返回当前时间
print(time.ctime(time.time()-86400)) --将时间戳转换为字符串
print(time.localtime(time.time()-86400)) --本地时间
print(time.mktime(time.localtime())) --与time.localtime()功能相反,将struct_time格式转回成时间戳格式
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())) -- 将struct_time格式转换指定d字符串格式
print(time.strptime("2016-01-28","%Y-%m-%d")) --将字符串格式转换成struct_time格式
time.sleep(5) 休眠5s

datetime 模块

常用的有:

import datetime

print(datetime.datetime.now())                                         # 2016-05-17 15:46:40.784376  获取当前的日期和时间
print(datetime.datetime.now()+datetime.timedelta(days=10))           # 2016-05-27 15:47:45.702528 将当前的时间向后推迟10天
print(datetime.date.today())           # 2016-05-17 获取当前的日期
print(datetime.datetime.utcnow())           # 2016-05-17 08:23:41.150628 获取格林威治时间 print(datetime.datetime.now().timetuple())                # time.struct_time(tm_year=2016 ... tm_hour=16,...)获取当前一个包含当前时间的结构体
print(datetime.datetime.now().timestamp())                # 1463473711.057878 获取当前的时间戳
print((datetime.datetime.fromtimestamp(1463473711.057878)))          # 2016-05-17 16:28:31.057878 将时间戳转换成日期和时间
print(datetime.datetime.strptime('2016-05-17 16:28:31','%Y-%m-%d %H:%M:%S')) #2016-05-17 16:28:31 str转换为datetime
print(datetime.datetime.now().strftime('%D, %m %d %H:%M')) #05/23/16, 05 23 10:10  datetime转换为str

定义的类有:

 datetime.date   --表示日期的类。常用的属性有year,month,day
datetime.time ---表示时间的类。床用的属性有hour,minute,second,microsecond
datetime.datetime --表示日期时间
datetime.timedalta --表示时间间隔,即两个时间点之间的长度
date类
date类表示日期,构造函数如下:
datetime.date(year,month,day);
year(1-9999)
month(1-12)
day(1-31)
date.today()--返回一个表示当前本地日期的date对象
date.fromtimestamp(timestamp) -- 根据给定的时间戳,返回一个date对象
date.year() -- 取给定时间的年
date.month() -- 取时间对象的月
date.day() -- 取给定时间的日
date.replace() -- 生成一个新的日期对象,用参数指定的年,月, 日代替原有对象中的属性
date.timetuple() -- 返回日期对应的time.struct_time对象
date.weekday() -- 返回week,Monday==0...Sunday == 6
date.isoweekday() -- 返回weekday,Monday == 1...Sunday == 7
date.ctime() -- 返回给定时间的字符串格式
print(datetime.date.today().year)  -- 取时间对象的年
print(datetime.date.today().month) --取时间对象的月
print(datetime.date.today().day) --取时间对象的日
print(datetime.date.today().replace(2010,6,12)) --生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性
print(datetime.date.today().timetuple()) 返回给定时间的时间元组/对象
print(datetime.date.today().weekday()) -- 返回weekday,从0开始
print(datetime.date.today().ctime) --返回给定时间的字符串格格式 .tiem类
time类表示时间,由时,分,秒以及微秒组成
time.min() --最小表示时间
time.max() --最大表示时间
time.resolution() -- 微秒
案例:
最大时间
print(datetime.time.max)
最小时间
print(datetime.time.min)
时间最小单位,微秒
print(datetime.time.resolution)
     ·datetime类
datetime是date与time的结合体,包括date与time的所有信息
datetime.max() --最大值
datetime.min() --最小值
datetime.resolution --datetime最小单位
datetime.today() -- 返回一个表示当前本地时间
datetime.fromtimestamp() --根据给定的时间戳,返回一个datetime对象
datetime.year() --取年
datetime.month() --取月
datetime.day() -- 取日期
datetim.replace() - 替换时间
datetime.strptime() --将字符串转换成日期格式
datetime.time() -- 取给定日期时间的时间
 案例:  

 print(datetime.datetime.max)         #datetime最大值  

 print(datetime.datetime.min)         #datetime最小值  

 print(datetime.datetime.resolution)   #datetime最小单位  

 print(datetime.datetime.today())     #返回一个表示当前本地时间  

 print(datetime.datetime.fromtimestamp(time.time()))#根据给定的时间戮,返回一个datetime对象  

 print(datetime.datetime.now().year)   #取时间对象的年  

 print(datetime.datetime.now().month)   #取时间对象的月  

 print(datetime.datetime.now().day)    #取时间对象的日  

 print(datetime.datetime.now().replace(2010,6,12))#生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性  

 print(datetime.datetime.now().timetuple())  #返回给定时间的时间元组/对象  

 print(datetime.datetime.now().weekday())  #返回weekday,从0开始  

 print(datetime.datetime.now().isoweekday())  #返回weekday,从1开始  

 print(datetime.datetime.now().ctime())    #返回给定时间的字符串格式  

 print(datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M"))#将字符串转换成日期格式  

 print(datetime.datetime.now().time())   #取给定日期时间的时间  

 print(datetime.datetime.now() + datetime.timedelta(days=-5))#获取5日前时间  

time和datetime时间戳---python的更多相关文章

  1. How to convert `ctime` to `datetime` in Python? - Stack Overflow

    How to convert `ctime` to `datetime` in Python? - Stack Overflow How to convert `ctime` to `datetime ...

  2. 实验吧-杂项-MD5之守株待兔(时间戳&python时间戳函数time.time())

    其实也有点蒙圈,因为从没做过和时间戳有关的题. 打开网站,将系统密钥解密得到一串值,而自己的密钥解密是空的,既然说是要和系统匹配,就把解密得到的值以get方式送出去. 但是发现还是在自己的密钥也发生了 ...

  3. python(6)时间戳和北京时间互转,输出当前的时间和推到七天前的日期

    项目发展的需要:(包含时间函数)time datetime 时间戳和北京时间互转 import time import datetime s = '2015-04-17 11:25:30' d = d ...

  4. Python之日期与时间处理模块(date和datetime)

    本节内容 前言 相关术语的解释 时间的表现形式 time模块 datetime模块 时间格式码 总结 前言 在开发工作中,我们经常需要用到日期与时间,如: 作为日志信息的内容输出 计算某个功能的执行时 ...

  5. python time、datetime、random、os、sys模块

    一.模块1.定义模块:用来从逻辑上组织Python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py,对应的模块名:test)包:用来从逻辑上组织 ...

  6. python时间模块datetime

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

  7. 【转】Python之日期与时间处理模块(date和datetime)

    [转]Python之日期与时间处理模块(date和datetime) 本节内容 前言 相关术语的解释 时间的表现形式 time模块 datetime模块 时间格式码 总结 前言 在开发工作中,我们经常 ...

  8. Python常用模块--datetime

    datetime是Python专门用于处理日期和时间的标准模块. 1.获取当前的本地时间 #!/usr/bin/env python# -*- coding:utf-8 -*-__author__ = ...

  9. Python时间与日期操作(datetime、time、calendar)

    相关模块 模块 说明 time time是一个仅包含与日期和时间相关的函数和常量的模块,在本模块中定义了C/C++编写的几个类.例如,struct_time类 datetime datetime是一个 ...

随机推荐

  1. BZOJ 1797: [Ahoi2009]Mincut 最小割

    1797: [Ahoi2009]Mincut 最小割 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2076  Solved: 885[Submit] ...

  2. 通过trie树单词自动补全(二)

    经常使用iciba进行单词查询, 关于他的搜索建议是通过单词前缀做的索引, 所以自己想动手实现下, 当然如果借助mysql的话,一条sql语句就能实现, 网上查询了下trie正适合做这个,所以通过C语 ...

  3. 利用DotSpatial发布WMS, WFS服务

    我们遇到的几个给政府部门做的GIS系统,一般都只要面子,只要好看,领导高兴得不得了,点点这里点点那里,哟,这按钮一点还会转,领导开心得跟朵花似的...要是搞个各种分析什么的全堆上来,他就嫌烦了...这 ...

  4. Android 图文数据JSON解析,金山词霸每日一句API的调用

    金山词霸开发的免费API http://open.iciba.com/dsapi/ 数据格式为 {","name":"\u7535\u5f71\u7ecf\u5 ...

  5. 一个五年 Android 开发者百度、阿里、聚美、映客的面试心经

    花絮 也许会有人感叹某些人的运气比较好,但是他们不曾知道对方吃过多少苦,受过多少委屈.某些时候就是需要我们用心去发现突破点,然后顺势而上,抓住机遇,那么你将会走向另外一条大道,成就另外一个全新的自我. ...

  6. win7 cmd 操作mysql数据库

    一 ,对MySql服务器的开启,重启,关闭等操作       当然,可以在win7的界面环境下,关闭或开启MySql服务.但是经常找不到win7的服务管理器,主要定位方法有二:命令行下输入servic ...

  7. 在finally中调用一个需要await的方法

    最近在把code改写成async+await的形式,发现有些情况下需要在finally中需要调用异步方法,但是编译器不允许在cache和finally中出现await关键字...但是用Wait()或者 ...

  8. gdb调试常用实用命令和core dump文件的生成

      1.生成core dump文件的方法: $  ulimit -c //查看是否为0 如果为0 $   ulimit -c unlimited 这样在程序崩溃以后会在当前目录生成一个core.xxx ...

  9. 转发 VS 重定向

    转发:JSP容器将使用一个内部的方法来调用目标页面,新的页面继续处理同一个请求,而浏览器将不会知道这个过程.以前的request中存放的变量全部失效,并进入一个新的request作用域. 重定向:第一 ...

  10. cocos2d-x 3.10 PageView BUG

    cocos2d-x 3.10 PageView 拖动滚动到下一个单元,没事件,3.11有修复.