I have a date in the format '%Y-%M-%d' for example '2017-08-01', that I'd like to convert to the format '%m-%d-%y' for example '8-1-2017'.
Only relevant examples I've found have been in php unfortunately.
from datetime import datetime
datetime.strptime("2017-08-01", '%Y-%m-%d').strftime('%m-%d-%y')
datetime.strptime("2017-08-01", '%Y-%m-%d')
#output
datetime.datetime(2017, 8, 1, 0, 0)
#output final
'08-01-17'
In the first part strptime , you are defining how the date is to you. In other words, you are turning your string into a datetime type instance. Then in the second part strftime you are formatting it the way you wish it to be.
Official definitions
date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format string.
Conversely, the datetime.strptime() class method creates
a datetime object from a string representing a date and
time and a corresponding format string.
Related
I'm trying to convert the list of str to the list of timestamps, then want to create the list of time delta of timestamps using total_seconds()
from datetime import datetime
a = ['091122333','092222222','093333333']
for i in a:
datetime.strptime(str(i),'%H:%M:%S.%f')
print(a)
It shows the error code of time data '091122333' does not match format '%H:%M:%S.%f'
I want to make timestamp 09(%H)11(%M)22(%S)333(%F) if possible.
Could you give me the advice above?
Thank you very much...
You have to first change the representation ( You have : which is not present in list of string in a) and how You manage what is returned from datetime.strptime (You have to store the value while You iterate through list) like that:
from datetime import datetime
a = ['091122333','092222222','093333333']
for t in range(len(a)):
a[t] = datetime.strptime(a[t],'%H%M%S%f')
delta = a[1]-a[0]
print(delta.total_seconds())
The format passed to strptime should represent the format used in the string (there are no colons in your string):
from datetime import datetime
a = ['091122333', '092222222', '093333333']
for i in a:
dt = datetime.strptime(str(i), '%H%M%S%f')
print(dt)
Out:
1900-01-01 09:11:22.333000
1900-01-01 09:22:22.222000
1900-01-01 09:33:33.333000
I've been trying to convert a timestamp that is a string to a datetime object. The problem is the timestamps formatting. I haven't been able to properly parse the timestamp using datetime.datetime.strptime. I could write my own little parser as its a simple problem but I was hoping to use strptime function, I just need help on the formatting.
Example
import datetime
formater = "%y-%m-%dT%H:%M:%SZ"
str_timestamp = "2021-03-13T18:27:37.60918Z"
timestamp = datetime.datetime.strptime(str_timestamp, formater)
print (timestamp)
Output
builtins.ValueError: time data '2021-03-13T18:27:37.60918Z' does not match format '%y-%m-%dT%H:%M:%SZ'
I'm clearly not symbolizing the formatter properly, the T and Z parts are what I can't account for.
y should be Y. y is for 2 digits year.
You should also take care for the milliseconds with .%f:
%Y-%m-%dT%H:%M:%S.%fZ
This format works:
formater = "%Y-%m-%dT%H:%M:%S.%fZ"
output:
2021-03-13 18:27:37.609180
I tried this:
timestamp = "2021-01-22T11:36:52.387000+01:00"
timestampObject = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
But gave me error:
ValueError: unconverted data remains: .150000+01:00
What is the rest reprisenting and how do I convert the rest? Also what does the 'T' mean?
Because you also have to supply a format specifier to take care of the trailing microseconds and timezone specifier, like the error is telling you, see Conversion of datetime string with microseconds and ...milliseconds. Probably you need '.fZ'. See the datetime doc.
Also, the 'T' just stands for 'Time'; it separates the date-field from the time-field, for ease in parsing (with sed/perl/grep/regex/etc.). Makes it easy if you wanted to a) locate datetimes within a log or b) throw away/separate the time part from the date part.
The string format you have is actually a datetime in ISO format. Luckily datetime has a function for handling that, you don't have to worry about supplying a format specifier for the trailing time objects...
Do you want only the date?
>>> datetime.datetime.fromisoformat("2021-01-22T11:36:52.387000+01:00").date()
datetime.date(2021, 1, 22)
Or do you want datetime?
>>> datetime.datetime.fromisoformat("2021-01-22T11:36:52.387000+01:00")
datetime.datetime(2021, 1, 22, 11, 36, 52, 387000, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))
This worked for me:
timestampObject = datetime.fromisoformat(
"2021-01-22T11:36:52.387000+01:00" ).date()
print('timestampObject.year: ', timestampObject.year)
timestampObject.year: 2021
I am trying to encode datetime format for strings that are of the form: '06JAN2018' or '31DEC2017'.
I think this is format = '%d[xxxx]%Y' but I don't know how to encode the month portion of it.
Is there a list anywhere of every type of encoding possible for this?
The list of these codes is in the datetime module's strftime() and strptime() Behavior documentation.
%b: Month as locale’s abbreviated name.
In your case, 06JAN2018 is %d%b%Y.
If what you're actually looking to do is to encode a datetime object or Pandas/NumPy datetime array to strings, you'll probably need to do the uppercasing yourself:
>>> dt = datetime.datetime(2017, 12, 31)
>>> dt.strftime('%d%b%Y').upper() # or .str.upper() in Pandas
'31DEC2017'
I have a string that contains the date in this format:
full_date = "May.02.1982"
I want to use datetime.strptime() to display the date in all digits like: "1982-05-02"
Here's what I tried:
full_date1 = datetime.strptime(full_date, "%Y-%m-%d")
When I try to print this, I get garbage values like built-in-67732
Where am I going wrong? Does the strptime() method not accept string values?
Your format string is wrong, it should be this:
In [65]:
full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)
You then need to call strftime on a datetime object to get the string format you desire:
In [67]:
dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'
strptime is for creating a datetime format from a string, not to reformat a string to another datetime string.
So you need to create a datetime object using strptime, then call strftime to create a string from the datetime object.
The datetime format strings can be found in the docs as well as an explanation of strptime and strftime