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.
You should use strptime: this function parses a string representing a time according to a format. The return value is a struct_time.
The format parameter defaults to %a %b %d %H:%M:%S %Y which matches the formatting returned by ctime().
So in your case just try the following line, since the default format is the one from ctime:
import datetime
import time
datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
Returns: datetime.datetime(2012, 4, 21, 4, 22, 00)
Try datetime.strptime()
.
See: http://docs.python.org/library/datetime.html#datetime.datetime.strptime
Locale information is not used by ctime().
Note: When using
time.ctime()
&datetime.fromtimestamp()
you might run into a historical issue when converting local timezones too. as stated in the comments of these answers here and here
Alternatively, If you need a "Date & Time" that you can format there are many ways using datetime, time.strftime, also, even using python pandas, and here posix_time, and lastly as mention on the other answers here datetime.strptime.
If you are not worried about timezones or the Julian Calendar, Ambiguous Times or converting to localtime using UNIXTIMESTAMP, looking to use EPOCH Time, be sure to specify Notable epoch dates in computing and this for unix
Which I thank Matt on this thread for the
"Please stop calling it "epoch time" when you mean Unix Time".......
Now as crazy as all that was, its not that bad. I have worked with many companies before, and this usually never comes up in the work place, as it usually has been dealt with.
So, aside from all that...This is My Personal Favorite:
I use this for my own stuff: time.strftime
from time import strftime
print(strftime('%Y%m%d_%H%M%S'))
Which I Return: Year, Month, Day, _, Hour, Minute, Second
20180827_021106
Which I use in a function:
def _now():
"""The Module Reports A Formatted Time."""
ymd = (strftime('%Y%m%d_%H%M%S'))
return ymd
Just something simple that keeps my logs in order.
Just use %c
:
datetime.datetime.strptime(time.ctime(), "%c")