This question already has answers here:
Python strftime - date without leading 0?
(21 answers)
Closed 5 years ago.
If I have a datetime object, how would I get the date as a string in the following format:
1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's
The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient and cumbersome. What would be a better way to accomplish this?
You could format it yourself instead of using strftime:
'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+
'%d/%d/%d' % (d.month, d.day, d.year)
The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings.
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior.
I have used lstrip('0') to remove the leading zero.
>>> d = datetime.datetime(1982, 1, 27)
>>> d.strftime("%m/%d/%y")
'01/27/82'
>>> d.strftime("%m/%d/%Y")
'01/27/1982'
>>> d.strftime("%m/%d/%Y").lstrip('0')
'1/27/1982'
Related
This question already has answers here:
Parse date string and change format
(10 answers)
Closed 3 years ago.
I realize this might be the most well-documented thing on the Internet but I can't seem to get it right. I have a string, '2019-10-16' that I want to turn into a date object so I can increase it incrementally, but can still be converted to the string '2019-10-06' again. However, I seem to only be able to get it as 2019.10.16 or something similar.
import datetime
day = '2019-10-16'
date_object = datetime.datetime.strptime(day, '%Y-%m-%d')
>date_object
>datetime.datetime(2019, 10, 16, 0, 0)
To change it use date_object.strftime('%Y-%m-%d')
This question already has answers here:
Python strftime - date without leading 0?
(21 answers)
How to convert a time to a string
(4 answers)
Closed 9 years ago.
In python how would I format the date as 1/1/1990?
dayToday = datetime.date(1990,1,1)
print dayToday
This returns 1990-01-01, but I want it to look like 1/1/1990. (Jan 1 1990)
Try to look into python datetime.strftime
dayToday = datetime.date(1990,1,1)
print dayToday.strftime('%Y/%m/%d')
>>> 1990/01/01
print dayToday.strftime('%Y/%b/%d')
>>> 1990/Jan/01
Use the datetime.strftime function with an appropriate format string:
>>> now = datetime.datetime.now()
>>> print now.strftime('%Y/%m/%d')
2013/04/19
Others have showed how to get the output 1990/01/01, but assuming you don't want the leading zeros in there, the only way that I know of to do it is to do the string formatting yourself:
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = dt.datetime.now())
'2013/4/19'
With the correct format and a without leading 0:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%-m/%-d/%Y")
'4/19/2013'
Reported to only work for Linux, but I haven't tested anything else personally.
Tested and working for 2.7.3 and 3.2.3 on Linux x64.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting string into datetime
What's a good way to convert a string of text (that represents a time) into a timestamp.
Times could come in various formats that are not predictable.
'January 2, 2012'
'2012-01-05 13:01:51'
'2012-01-01'
All outputs should be timestamps:
1325480400
1325786511
1325394000
The time.strptime() function requires that inputs be consistent. I'm parsing a list of user-submitted dates that have various time formats.
Use time.strptime()
>>> int(mktime(strptime('January 2, 2012', '%B %d, %Y')))
1325422800
>>> int(mktime(strptime('2012-01-05 13:01:51', '%Y-%m-%d %H:%M:%S')))
1325728911
>>> int(mktime(strptime('2012-01-05', '%Y-%m-%d')))
1325682000
You want time.strptime()
http://docs.python.org/library/time.html#time.strptime
In addition: check out dateutil.parse()
http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2
In addition: do your own research:
Converting string into datetime
In addition: parsing date strings can be ambigious: what does 08-12-2012 mean? August 12th? 8th of December?
Check out this post :
What is the formula for calculating a timestamp?
it's in PHP but does the job
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a time to a string
I have a variable as shown in the below code.
a = "2011-06-09"
Using python, how to convert it to the following format?
"Jun 09,2011"
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
#Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
This question already has answers here:
Display number with leading zeros [duplicate]
(19 answers)
Closed 6 months ago.
In Python, how do I specify a format when converting int to string?
More precisely, I want my format to add leading zeros to have a string
with constant length. For example, if the constant length is set to 4:
1 would be converted into "0001"
12 would be converted into "0012"
165 would be converted into "0165"
I have no constraint on the behaviour when the integer is greater than what can allow the given length (9999 in my example).
How can I do that in Python?
"%04d" where the 4 is the constant length will do what you described.
You can read about string formatting here.
Update for Python 3:
{:04d} is the equivalent for strings using the str.format method or format builtin function. See the format specification mini-language documentation.
You could use the zfill function of str class. Like so -
>>> str(165).zfill(4)
'0165'
One could also do %04d etc. like the others have suggested. But I thought this is more pythonic way of doing this...
With python3 format and the new 3.6 f"" notation:
>>> i = 5
>>> "{:4n}".format(i)
' 5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
' 5'
>>> f"{i:04n}"
'0005'
Try formatted string printing:
print "%04d" % 1 Outputs 0001
Use the percentage (%) operator:
>>> number = 1
>>> print("%04d") % number
0001
>>> number = 342
>>> print("%04d") % number
0342
Documentation is over here
The advantage in using % instead of zfill() is that you parse values into a string in a more legible way:
>>> number = 99
>>> print("My number is %04d to which I can add 1 and get %04d") % (number, number+1)
My number is 0099 to which I can add 1 and get 0100