python datetime模块相关 mysql 时间戳等

来源:互联网 发布:win10系统优化固态 编辑:程序博客网 时间:2024/05/21 15:10

(转载)http://blog.csdn.net/power0405hf/article/details/48574045

原文在此 
所有日期,时间的API都在datetime模块内。

1.日期输出格式化

strftime()函数将datetime结构格式化为一个字符串datetime =>stringnow = datetime.datetime.now()now.strftime('%Y-%m-%d %H:%M:%S')
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
转换控制符说明%a星期几的简写形式%A星期几的全称%b月份的简写形式%B月份的全称%c日期和时间%d月份中的日期,0-31%H小时,00-23%I12进制小时钟点,01-12%j年份中的日期,001-366%m年份中的月份,01-12%M分,00-59%p上午或下午%S秒,00-60%u星期几,1-7%w星期几,0-6%x当地格式的日期%X当地格式的时间%y年份中的最后两位数,00-99%Y年%Z地理时区名称

strptime

import timet = time.time()print t1202872416.4920001print type(t)<type 'float'>t = time.localtime()print t(2008, 2, 13, 10, 56, 44, 2, 44, 0)print type(t)<type 'time.struct_time'>print time.strftime('%Y-%m-%d', t)'2008-02-13'print time.strptime('2008-02-14', '%Y-%m-%d')(2008, 2, 14, 0, 0, 0, 3, 45, -1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2.日期转为时间戳

#设a为字符串import timea = "2011-09-28 10:00:00"#将"2011-09-28 10:00:00"转化为时间戳time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))1317091800.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.mysql 时间

1、将时间转换为时间戳

select unix_timestamp(‘2009-10-26 10-06-07’)

如果参数为空,则处理为当前时间

2、将时间戳转换为时间

select from_unixtime(1256540102)



//------------------------------------------------------------------------------------------------

now = datetime.datetime.now()nowStr = now.strftime('%Y-%m-%d %H:%M:%S')
相当于mysql中的now()函数

原创粉丝点击