参考网址,写的很棒:

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. angular监听

    监听中第三个参数,何时使用true? true的意思是“深度监听” 1.当监听对象属性变化时,而你监听的对象写得是对象,此时要用深度监听true: 2....... 监听耗资源,用完关闭 var wa ...

  2. Java里的生产者-消费者模型(Producer and Consumer Pattern in Java)

    生产者-消费者模型是多线程问题里面的经典问题,也是面试的常见问题.有如下几个常见的实现方法: 1. wait()/notify() 2. lock & condition 3. Blockin ...

  3. 【SQL】sql server 2008R2 评估期已过,

    参考1:http://www.cnblogs.com 参考2:http://www.wang1314.com 个人认为:升级+秘钥,,买正版才是最终的解决方法.

  4. 腾讯云CentOS Apache开启HTTPS

    1.申请SSL证书 https://console.qcloud.com/ssl?utm_source=yingyongbao&utm_medium=ssl&utm_campaign= ...

  5. Could not execute action

    2.Could not execute action 原因:action成员变量有空值,要访问方法中,使用了该成员变量 参考: http://www.blogjava.net/javagrass/ar ...

  6. Synchronized

    1. 在编写一个类时,如果该类中的代码可能运行与多线程环境下,就要考虑同步问题了. 会同时被多个线程访问的资源,就是竞争资源,也称为竞争条件.对于多线程共享的资源我们必须进行同步,以避免一个线程的改动 ...

  7. bzoj 1305 dance跳舞

    最大流. 首先二分答案,问题转化为x首舞曲是否可行. 考虑建图,对每个人建立三个点,分别表示全体,喜欢和不喜欢. 源点向每个男生全体点连一条容量为x的边. 每个男生整体点向喜欢点连一条容量为正无穷的边 ...

  8. bc#54 div2

    用小号做的div2 A:竟然看错了排序顺序...白白WA了两发 注意读入一整行(包括空格):getline(cin,st) [gets也是资瓷的 #include<iostream> us ...

  9. node 常用命令

    nvm nvm list  列出安装的node npm install -g cnpm --registry=https://registry.npm.taobao.org  安装cnpm npm i ...

  10. RabbitMQ Lazy Queue 延迟加载

    Lazy Queue 在著名的单例设计模式中就有懒汉式的实现方式,也就是只有在你需要的时候我才去加载. 这让博主想到了以前上学的时候,每到了假期的假期作业,在假期的时候是从来不做的.只有在快开学老师要 ...