Problem with format datetime in python

I have problem with formatting date. This is my code:

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'))

At my last line I get exception:

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

What's wrong with this?

EDIT To be more clear, this is my entire code which is mix of what I find on 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())

I'm trying to get random date of birth for adult.

I'm using Windows XP.

-------------Problems Reply------------

I'm trying to get random date of birth for adult.

OK, so if you say than an adult can be between 18 and 75 years old (6571 - 27375 days), then let's find a date that is so many days ago from today:

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'))

Indeed, you'll hit the OverflowError because you're going beyond the unix epoch. A simple solution would be to refactor your code to use datetime and timedelta objects, there you'll have no problem with date ranges. I did the refactoring myself and it seems to be working (Note that I'm not taking into consideration the subleties of timezones).

from datetime import datetime, timedelta
import random

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.
"""

sdatetime = datetime.strptime(start, format)
edatetime = datetime.strptime(end, format)

# get time delta and calculate new delta in days * prop
delta = edatetime - sdatetime # this is a timedelta
propdelta = timedelta(days = prop * delta.days)

pdatetime = sdatetime + propdelta
return pdatetime.strftime(format)

def randomDate(start, end, prop):
return strTimeProp(start, end, '%Y-%m-%d %H:%M:%S.%f', prop)

b1=datetime.now()
print b1
startDate=b1-timedelta(27375)
print startDate
endDate=b1-timedelta(6571)
print endDate
randomDate=randomDate(str(startDate), str(endDate), random.random())
print randomDate

Hope it helps.

The first argument to time.strptime() needs to be a string, not a datetime object you get back from datetime.datetime.now()

Change your last line to:

stime = time.mktime(time.strptime(str(myDate), '%Y-%m-%d %H:%M:%S.%f'))

(The code in your edit does convert the datetime object to a string though)

Category:python Views:0 Time:2011-02-02

Related post

  • Read a formatted date in Python 2.3? 2009-12-18

    I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format '10-JUL-2010' then subtract a day (I would use timedelta), and return the string '09-JUL-2010 00:00:00 ET' of course, this

  • Specifying zero padding with format-dateTime 2010-01-12

    I have the following in xslt <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/02/xpath-function

  • How would you format DateTime in international format? 2010-06-29

    The international string representation format is (YYYY-MM-DD HH:MM:SS ±HHMM). e.g. 2010-06-10 21:21:10 -0400 basically the problem I am having is figuring out how to get the difference from GMT. DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

  • How to convert string to datetime in python 2011-03-07

    I have a date string in following format 2011-03-07 how to convert this to datetime in python? --------------Solutions------------- Try the following code, which uses strptime from the datetime module: from datetime import datetime datetime.strptime(

  • How to control appearance of ':' in time zone offset when parsing/formatting Datetime 2011-03-09

    I'm working with a protocol that may optionally include a time zone offset when specifying datetime information. My code is written in C# and we are using the 4.0 .NET runtime. I see that there is a formatting option "zzz" for including timezone info

  • Converting a string to datetime in python 2011-07-15

    Possible Duplicate: Parse date and format it using python? i have a date string like 2011-07-15 13:00:00+00:00 . Any way to convert this string to a datetime object in python ? Thank You --------------Solutions------------- You can handle the time zo

  • Calling a function at datetime in Python 2011-09-14

    What is a good way to call a function at datetime in Python? There 3 ways that I know of: "Are we there yet?!" (check at if date has passed at interval (time.sleep(interval))) This is obviously bad. It can only be precise if interval is low, which be

  • Html.HiddenFor formats DateTime incorrectly in ASP.NET 2012-03-15

    I'm writing an ASP.NET MVC3 application in C# and have found that calling Html.HiddenFor in my view will render a DateTime differently (and incorrectly) to if i was to call Html.DisplayFor. The model its taking the value from does have a DisplayForma

  • How to convert `ctime` to `datetime` in Python? 2012-04-21

    import time t = time.ctime() For me at the moment, t is 'Sat Apr 21 11:58:02 2012'. I have more data like this. My question is: How to convert t to datetime in Python? Are there any modules to to it? I tried to make a time dict and then convert t, bu

  • Convert date to datetime in Python 2009-12-21

    Silly question, but is there a built-in method for converting a date to a datetime in Python, ie. getting the datetime for the midnight of the date? The opposite conversion is easy - datetime has a .date() method. Do I really have to manually call da

  • XSLT2 format-dateTime - AM/PM without dots/periods 2010-06-22

    This is a question for XSLT 2 format-dateTime function. Please can anyone tell me how to make A.M./P.M. display with not dots/periods (AM/PM)? <xsl:variable name="ampm" select="format-dateTime(DATE, '[PN]')"/> The below code returns blank? <

  • Telerik MVC Grid - problem with nullable DateTime property 2010-11-17

    I am reasonably new to Telerik MVC extensions. I have implemented my first instance in a view successfully. I am not implementing my second view using the Telerik MVC Grid, however the class that is being bound to the grid has 2 columns which are of

  • convert string to datetime in python 2011-04-19

    Possible Duplicate: Convert string to datetime in django? how to convert time string like '18:30:00' into datetime in python? --------------Solutions------------- Use the datetime.datetime.strptime() method My post in Daniweb: Date string to date obj

  • perl - formatting DateTime output 2011-11-27

    How do I convert my return using DateTime from: This is my date:2011-11-26T20:11:06 to This is my date:20111126 Using this existing code: use DateTime qw(); my $dt3 = DateTime->now->subtract(days => 1); print "This is my date:$dt3\n" -------

  • Hello group, I have a problem in format device that Dell 2012-07-04

    Hello group, I have a problem in formate device that Dell n5050 after downloading Windows blue screen Is there a way --------------Solutions------------- Please explain exactly what your problem is!! Your not saying anything here

  • Consuming the pickle binary format from non-python (with celery and rabbitmq) 2012-08-29

    I'm using Python, Celery and RabbitMQ to produce messages from loosely coupled systems. However, I'm worried about interoperability. When inspecting the message payload directly from RabbitMQ, that is produced by celery, I get the following binary fo

  • asp.net mvc format DateTime in whole application 2014-01-30

    So basically, what I want is to format DateTime in whole application and show it in a specific format in the whole Web App. Is there any better solution to just write ToString("{0:stringformathere}", obj)? --------------Solutions------------- Try to

  • Problems trying to format currency with Python (Django) 2010-06-01

    I have the following code in Django: import locale locale.setlocale( locale.LC_ALL, '' ) def format_currency(i): return locale.currency(float(i), grouping=True) It work on some computers in dev mode, but as soon as I try to deploy it on production I

  • python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S" 2010-09-04

    I would like a python datetime object to output (and use the result in django) like this: Thu the 2nd at 4:30 But I find no way in python to output st, nd, rd, or th like I can with PHP datetime format with the S string (What they call "English Ordin

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.130 (s). 11 q(s)