2

Actually I am a newbie in python and there is the code that worries me a lot.

import time
from datetime import time, date, datetime

createdAt ='Wed Jan 12 11:45:28 +0000 2011' # createdAt value is read from a file
print 'CR= ',createdAt
struct_time = datetime.strptime(str(createdAt),'%a %b %d %H:%M:%S +0000 %Y').strftime('%s') # notice small s here
print "returned tuple: %s " % struct_time

I am getting an error like this in my compiler Python 2.7.10 Shell

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    asd = datetime.strptime(str(createdAt),'%a %b %d %H:%M:%S +0000 %Y').strftime('%s')
ValueError: Invalid format string

but in online compiler I am getting an output like this (online compiler at https://ideone.com/g0R2xw)

CR=  Wed Jan 12 11:45:28 +0000 2011
returned tuple: 1294832728

I want my output to be this. Also if you can kindly tell me how this is calculated. Thank You in advance...

Paul92
  • 137
  • 2
  • 7
  • With respect to using `.strftime(%s)` see http://stackoverflow.com/a/31096353/4663466 or more comprehensive answer http://stackoverflow.com/a/8778548/4663466. In short, don't use `.strftime(%s)` for unix time / seconds since epoch. – Scott Jul 03 '15 at 05:57

1 Answers1

0

From the documentation -

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

So the issue is that strftime() can behave differently based on the platform in which it is used.

Python directly does not support any %s (small s) , but seems like the linux system supports it , which could be why it is working in the online compiler, which inturn may be hosted on an linux environment. It worked in my linux envrionment as well.

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> (datetime.datetime.strptime(str(createdAt),'%a %b %d %H:%M:%S +0000 %Y') - datetime.datetime(1970,1,1)).total_seconds()
1294832728.0
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176