👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I must have the current year and month in datetime.
I use this:
datem = datetime.today().strftime("%Y-%m") datem = datetime.strptime(datem, "%Y-%m")
Is there maybe another way?
👻 Read also: what is the best laptop for engineering students?
Python strftime - date without leading 0?
When using Python
strftime, is there a way to remove the first 0 of the date if it"s before the 10th, ie. so
1? Can"t find a
%thingy for that?
Actually I had the same problem and I realized that, if you add a hyphen between the
% and the letter, you can remove the leading zero.
This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use
Convert python datetime to epoch with strftime
I have a time in UTC from which I want the number of seconds since epoch.
I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.
1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.
So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?
How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds() 1333238400.0
In Python 3.3+ you can use
>>> datetime.datetime(2012,4,1,0,0).timestamp() 1333234800.0
Why you should not use
Python doesn"t actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it"s not in the list), the only reason it"s working is because Python is passing the information to your system"s strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime("%s") "1333234800"
How can I account for period (AM/PM) using strftime?
Specifically I have code that simplifies to this:
from datetime import datetime date_string = "2009-11-29 03:17 PM" format = "%Y-%m-%d %H:%M %p" my_date = datetime.strptime(date_string, format) # This prints "2009-11-29 03:17 AM" print my_date.strftime(format)
What gives? Does Python just ignore the period specifier when parsing dates or am I doing something stupid?
time.strftime docs say:
When used with the strptime() function, the
%pdirective only affects the output hour field if the
%Idirective is used to parse the hour.
Sure enough, changing your
%I makes it work.