Python datetime.strptime - Converting month in String format to Digit - python

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

Related

Subtracting datetime in string format with datetime format

I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.
You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325
The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.

Convert string to timestamp python

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

convert date in one format to another format

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.

Is there a way to extract time from datetime objects in Python?

I want to extract time values from a datetime object in Python. This is the code I used:
t = '2018-12-16 17:59:00'
t.strftime('%H:%M:%S')
There is clearly something wrong with the code because I am getting this error:
AttributeError: 'str' object has no attribute 'strftime'
I am using Python 3 and I need to convert around 30000 datetime values.
from datetime import datetime as dt
t = '2018-12-16 17:59:00'
t = dt.strptime(t, '%Y-%m-%d %H:%M:%S')
print(t.strftime('%H:%M:%S'))
in datetime methods
strptime is the mehtod to convert from string to datetime
strftime is the method to convert from datetime to string
That's a string, not a datetime object. You should probably be using a datetime object:
t = datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
But if you want to use your string, you can splice it into two (space-separated) parts:
t = t.split() # t = ['2018-12-16', '17:59:00']
Then take the first part:
date = t[0]

Convert date to ordinal python?

I want to convert
2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()
from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()
Thanks in advance
You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832
The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.
like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
You need to firstly convert the time string to datetime object using strptime(). Then call .toordinal() on the datetime object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773
It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
return datetime.strptime(date, '%Y-%M-%d').toordinal()
convert_date_to_ordinal('2010-03-01')
#returns: 733773

Categories

Resources