参考网址,写的很棒:

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. 面向移动设备的html5开发框架

    很久以前整理了篇将手机网站做成手机应用的JS框架.时隔一年多,很多新的技术已经出现,下面再来总结下还有哪些框架是适合面向手机设备的开发的. 1.jQuery Mobile jQuery Mobile ...

  2. DayPilot 7.8 DLL去DEMO字样下载

    来自 DayPilot 的 7.8.3169.1 版本的DLL,微调去掉了“DEMO”字样,供参考,商用请支持正版! 此处下载: http://files.cnblogs.com/files/pcca ...

  3. airline 設定 安裝

    .vimrc " install airline plugin using Vundle Plugin 'vim-airline/vim-airline' " install ai ...

  4. 扩展htmlhelper.DropDownListFor 支持list数据源和option增加属性

    mvc自带的DropDownListFor数据源必须是IEnumerable<SelectListItem>.并且option不支持增加自定义属性.在使用bootstrap-select组 ...

  5. ubuntu下配置vpn

    Ubuntu系统下搭建VPN环境 以下是基于Amazon EC2/Ubuntu搭建PPTPD服务提供VPN连接的过程记录.至于为什么要搞VPN,大家都懂的...而我主要是要访问Python的一些网站以 ...

  6. ORB-SLAM(三)地图初始化

    单目SLAM地图初始化的目标是构建初始的三维点云.由于不能仅仅从单帧得到深度信息,因此需要从图像序列中选取两帧以上的图像,估计摄像机姿态并重建出初始的三维点云. ORB-SLAM中提到,地图初始化常见 ...

  7. u盘安装系统教程详解

    一.准备阶段 提前准备一个至少1G或以上的u盘,方便好用. 1.制作u盘启动工具 (1)工具下载,推荐IT天空的优启通 下载地址:https://www.itiankong.net/thread-37 ...

  8. Codeforces Round #342 (Div. 2) B. War of the Corporations(贪心)

    传送门 Description A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Go ...

  9. Structure Of Management Information - SNMP Tutorial

    30.6 The Structure Of Management Information In addition to the standards that specify MIB variables ...

  10. Java数据结构——带权图

    带权图的最小生成树--Prim算法和Kruskal算法 带权图的最短路径算法--Dijkstra算法 package graph; // path.java // demonstrates short ...