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

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

Python代码   收藏代码
  1. import time  
  2.   
  3. #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)  
  4. print time.localtime() #返回tuple  
  5.   
  6. #2012-09-15 15:01:44  
  7. print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())  
  8.   
  9. #2012-09-15 03PM 01:44 今天是当年第259天  当年第37周  星期6  
  10. print time.strftime("%Y-%m-%d %I%p %M:%S 今天是当年第%j天  当年第%U周  星期%w",time.localtime())  
  11.   
  12. #1347692504.41 [秒数]:double  
  13. print time.time()  
  14.   
  15.   
  16.   
  17. #指令    含义   
  18. #     
  19. #%Y    有世纪的年份,如2012  
  20. #%m    十进制月份[01,12].     
  21. #%d    当月的第几天 [01,31].     
  22. #%H    24进制的小时[00,23].     
  23. #%M    十进制分钟[00,59].     
  24. #%S    秒数[00,61]. 61是有闰秒的情况   
  25. #  
  26. #%w    十进制的数字,代表周几 ;0是周日,1是周一.. [0(Sunday),6].     
  27. #  
  28. #%I    十二进制的小时[01,12].     
  29. #%p    上午还是下午: AM or PM. (1)   
  30. #  
  31. #%j    当年第几天[001,366].     
  32. #%U    当年的第几周[00,53] 0=新一年的第一个星期一之前的所有天被认为是在0周【周日是每周第一天】  
  33. #%W    当年的第几周[00,53] 0=新一年的第一个星期一之前的所有天被认为是在0周【周一是每周第一天】  
  34. #   
  35. #%y    无世纪的年份[00,99].  如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. 秒数 ->[tuple]-> 年月日串
birth_secds = 485749800
tup_birth = time.localtime(birth_secds)
format_birth = time.strftime("%Y-%m-%d %H:%M:%S",tup_birth)
# 2. 年月日串 ->[tuple]-> 秒数
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

猜你喜欢

转载自www.cnblogs.com/stevenliu1030/p/10494873.html