hyytaojunming 发表于 2017-5-3 09:09:38

python中的时间和时间格式转换

  1.python中的时间:
要得到年月日时分秒的时间:

import time
#time.struct_time(tm_year=2012, tm_mon=9, tm_mday=15, tm_hour=15, tm_min=1, tm_sec=44, tm_wday=5, tm_yday=259, tm_isdst=0)
print time.localtime() #返回tuple
#2012-09-15 15:01:44
print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
#2012-09-15 03PM 01:44 今天是当年第259天当年第37周星期6
print time.strftime("%Y-%m-%d %I%p %M:%S 今天是当年第%j天当年第%U周星期%w",time.localtime())
#1347692504.41 [秒数]:double
print time.time()

#指令    含义
#   
#%Y    有世纪的年份,如2012
#%m    十进制月份.   
#%d    当月的第几天 .   
#%H    24进制的小时.   
#%M    十进制分钟.   
#%S    秒数. 61是有闰秒的情况
#
#%w    十进制的数字,代表周几 ;0是周日,1是周一.. .   
#
#%I    十二进制的小时.   
#%p    上午还是下午: AM or PM. (1)
#
#%j    当年第几天.   
#%U    当年的第几周 0=新一年的第一个星期一之前的所有天被认为是在0周【周日是每周第一天】
#%W    当年的第几周 0=新一年的第一个星期一之前的所有天被认为是在0周【周一是每周第一天】
#
#%y    无世纪的年份.如12年
  2.格式转换
  #============================
  # 时间格式time的方法:
  # localtime(秒数)    # :秒数-->time.struct_time
  # mktime(time.struct_time)    #:time.struct_time-->秒数
  # strftime("格式串",time.struct_time)    #:time.struct_time -->"yyyy-mm-dd HH:MM:SS"
  # strptime(tuple_日期,"格式串")     #:"yyyy-mm-dd HH:MM:SS"-->time.struct_time
  #============================
  # 1. 秒数 ->-> 年月日串
birth_secds = 485749800
tup_birth = time.localtime(birth_secds)
format_birth = time.strftime("%Y-%m-%d %H:%M:%S",tup_birth)
# 2. 年月日串 ->-> 秒数
print format_birth#1985-05-24 10:30:00
  format_birth = "1985-05-24 10:30:00"
tup_birth = time.strptime(format_birth, "%Y-%m-%d %H:%M:%S");
birth_secds = time.mktime(tup_birth)
print birth_secds#485749800.0
页: [1]
查看完整版本: python中的时间和时间格式转换