Skip to main content
 首页 » 编程设计

python之python格式日期时间的问题

2025年05月04日14shanyou

我在格式化日期时遇到问题。这是我的代码:

myDate=datetime.datetime.now() 
print myDate #2011-02-02 13:54:26.162000 
stime = time.mktime(time.strptime(myDate, '%Y-%m-%d %I:%M%S.%f')) 

在我的最后一行我得到了异常:

File "c:\Python27\Lib\_strptime.py", line 322, in _strptime 
  found = format_regex.match(data_string) 

这是怎么回事?

编辑 更清楚地说,这是我的整个代码,它是我在 stackoverflow 上找到的内容的混合:

import random 
import time 
 
def strTimeProp(start, end, format, prop): 
    """Get a time at a proportion of a range of two formatted times. 
 
    start and end should be strings specifying times formated in the 
    given format (strftime-style), giving an interval [start, end]. 
    prop specifies how a proportion of the interval to be taken after 
    start.  The returned time will be in the specified format. 
    """ 
 
    stime = time.mktime(time.strptime(start, format)) 
    etime = time.mktime(time.strptime(end, format)) 
 
    ptime = stime + prop * (etime - stime) 
 
    return time.strftime(format, time.localtime(ptime)) 
 
 
def randomDate(start, end, prop): 
    return strTimeProp(start, end, '%Y-%m-%d %H:%M:%S.%f', prop) 
 
b1=datetime.datetime.now() 
print b1 
startDate=b1-datetime.timedelta(27375) 
print startDate 
endDate=b1-datetime.timedelta(6571) 
print endDate 
randomDate=randomDate(str(startDate), str(endDate), random.random()) 

我正在尝试获取成人的随机出生日期。

我使用的是 Windows XP。

请您参考如下方法:

我正在尝试获取成人的随机出生日期。

好吧,如果你说一个成年人的年龄可以在 18 到 75 岁之间(6571 - 27375 天),那么让我们找出从今天算起很多天前的日期:

from datetime import datetime, timedelta 
import random 
 
birthday = datetime.today() - timedelta(days = random.randrange(6571, 27375)) 
 
print 'Person was born on %s' % (birthday.strftime('%Y-%m-%d'))