In Python, we can convert a date to a string by:
>>> import datetime
>>> datetime.date(2002, 12,4).isoformat()
'2002-12-04'
How can we format the output to be '20021204', i.e. without dashes?
There are two functions, but I don't know how to specify the format:
date.strftime(format)
Return a string representing the date,
controlled by an explicit format string. Format codes referring to
hours, minutes or seconds will see 0 values. For a complete list of
formatting directives, see section strftime() and strptime() Behavior.
and
date.__format__(format)
Same as date.strftime(). This makes it
possible to specify format string for a date object when using
str.format(). See section strftime() and strptime() Behavior.
You are using the wrong tool for your job, use strftime
>>> datetime.date(2002, 12,4).strftime("%Y%m%d")
'20021204'
For details on using strftime and strptime, refer strftime() and strptime() Behavior
For your particular case, I will quote the relevant excerpt
%Y Year with century as a decimal number. 1970, 1988, 2001, 2013
%m Month as a zero-padded decimal number. 01, 02, ..., 12
%d Day of the month as a zero-padded decimal number. 01, 02, ..., 31
alternatively, you could have always removed or replaced the hyphen from the isoformat
>>> str(datetime.date(2002, 12,4)).translate(None,'-')
'20021204'
You can use '%m%d%Y as your format :
>>> d=datetime.date(2002, 12,4)
>>> d.strftime('%m%d%Y')
'12042002'
Or in your first code, you can use str.replace :
>>> datetime.date(2002, 12,4).isoformat().replace('-','')
'20021204'
Related
I expected datetime.strftime and datetime.strptime calls to be reversible. Such that calling
datetime.strptime(datetime.now().strftime(fmt), fmt))
Would give the closest reconstruction of now() (given the information preserved by the format).
However, this is not the case when formatting a date to a string with a YYYY-Week# format:
>>> yyyy_u = datetime.datetime(1992, 5, 17).strftime('%Y-%U')
>>> print(yyyy_u)
'1992-20'
Formatting the string back to a date does not give the expected response:
>>> datetime.datetime.strptime(yyyy_u, '%Y-%U')
datetime.datetime(1992, 1, 1, 0, 0)
I would have expected the response to be the first day of week 20 in 1992 (17 May 1992).
Is this a failure of the %U format option or more generally are datetime.strftime and datetime.strptime calls not meant to be reversible?
From the Python docs regarding strptime() behaviour:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Day of the week must be specified along with Week number and Year.
(%Y-%U-%w)
datetime.datetime.strptime('1992-20-0', '%Y-%U-%w') gives the first day of week 20 for 1992 year.
In this documentation , strftime appear 3 times. One implementation in "date" library, one in "datetime" library, and one in the "time" library.
All descriptions of this function refer to the same part of the page about the behavior of this function.
So when should we use time.strftime, date.strftime or datetime.strftime? Is their any difference in practice? Do we change only for clarity's sake.
I will quote from the documentation.Refer the code to understand better.
time.strftime(format)
Return a string representing the time, controlled by an explicit format string. For a complete list of formatting .
>>> t = time(12, 10, 30, tzinfo=GMT1())
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 Europe/Prague'
datetime.strftime(format)
Return a string representing the date and time, controlled by an explicit format string.
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
date.strftime(format)
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values.
>>> d = date.fromordinal(730920)
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
I have the following python snippet:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object
However when I execute the code, I'm getting the following error:
ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'
what's wrong with my matching expression?
EDIT 2: According to this post, strptime doesn't support %z (despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)
Gives the following output:
$ python date.py
2015-01-05 17:47:59
EDIT: Your datetime.strptime argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'
With strptime(), %y refers to
Year without century as a zero-padded decimal number
I.e. 01, 99, etc.
If you want to use the full 4-digit year, you need to use %Y
Similarly, if you want to use the 3-letter month, you need to use %b, not %m
I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
And UTC offset is lowercase z.
I am trying to use the DateTime module and I can never get it to work for this code:
class Loan:
def __init__(self, person_name, bookLoaned, loanStart, loanEnd):
self.personName = person_name
self.bookLoaned = bookLoaned
self.loanStart = datetime.date(loanStart)
self.loanEnd = datetime.date(loanEnd)
For some reason, PyScripter is giving an error "TypeError:an integer is required (got type str)".
I call Loan like this:
loan1 = Loan(borrower1.name, BookCopy1.title, ("22/06/2016"), ("22/06/2018"))
I'm expecting it to be some sort of syntax error (which is why I thought it'd only be necessary to post the method and not the entire script)
Can someone please help?
Let's see:
>>> import datetime
>>> help(datetime.date)
Help on class date in module datetime:
class date(builtins.object)
| date(year, month, day) --> date object
:
>>> datetime.date(2016,6,22)
datetime.date(2016, 6, 22)
date doesn't take a string. Looking at help(datetime), strptime sounds like what you want:
>>> help(datetime.datetime.strptime)
Help on built-in function strptime:
strptime(...) method of builtins.type instance
string, format -> new datetime parsed from a string (like time.strptime()).
This function takes a string like you want, but also a format. Let's see what time.strptime has to say about formatting:
>>> import time
>>> help(time.strptime)
Help on built-in function strptime in module time:
strptime(...)
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
So a datetime object can be created from a string and an appropriate format:
>>> datetime.datetime.strptime('22/06/2016','%d/%m/%Y')
datetime.datetime(2016, 6, 22, 0, 0)
but you want a date only. Looking back at the help for datetime.datetime, it has a date() method:
>>> datetime.datetime.strptime('22/06/2016','%d/%m/%Y').date()
datetime.date(2016, 6, 22)
For your code (as an MCVE):
import datetime
def date_from_string(strdate):
return datetime.datetime.strptime(strdate,'%d/%m/%Y').date()
class Loan:
def __init__(self, person_name, bookLoaned, loanStart, loanEnd):
self.personName = person_name
self.bookLoaned = bookLoaned
self.loanStart = date_from_string(loanStart)
self.loanEnd = date_from_string(loanEnd)
loan1 = Loan('John doe', 'Book Title', "22/06/2016", "22/06/2018")
Here's an example of how the Facebook Graph API is returning date strings for me:
2011-03-06T03:36:45+0000
how would I parse this into a python datetime class? I'm aware of the datetime.strptime function, which takes in a second parameter that contains some googly-eyed format string, but don't know which letters and dashes to include.
Here it is with time & strptime:
>>> time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')
time.struct_time(tm_year=2011, tm_mon=3, tm_mday=6, tm_hour=3, tm_min=36, tm_sec=45, tm_wday=6, tm_yday=65, tm_isdst=-1)
or with datetime:
>>> datetime.datetime.strptime('2011-03-06T03:36:45+0000','%Y-%m-%dT%H:%M:%S+0000')
As you see it returns the time_struct with the fields correctly filled out.
Here is a translation of the format:
%Y = year with century (2011)
%m = month w/ leading zero
%d = day w/ leading zero
%H = hour w/ leading zero, 24-hour clock
%M = minute
%S = second
T, -, and : are used as delimiters, and included as literal strings
+0000 is again included as a literal string
In [10]: datetime.datetime.strptime('2011-03-06T03:36:45+0000','%Y-%m-%dT%H:%M:%S+0000')
Out[10]: datetime.datetime(2011, 3, 6, 3, 36, 45)