Python convert string to datetime in variable formats - python

I am generating date and time information which is string from an API. The generated string is in your system's date/time format by default (Win 10 in my case). For example if you are using MM/DD/YYYY HH:MM:SS tt in your computer, the generated string would be something like "05/07/2019 06:00:00 AM".
For comparison purpose, I would then convert the string to datetime format by using datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p"). This works prefectly fine, however if someone else whose system date/time format is different from' MM/DD/YYYY HH:MM:SS tt' runs my script, he would get a mismatch error as the string can no longer be converted by %m/%d/%Y %I:%M:%S %p.
So would it be possible to make the desired datetime format become a variable argument in the strptime function? Or even simpler, just make the format to be the same as the system's date/time format.

You can use try and except to fix this (although there might be another way)
try:
datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p")
except TypeError:
try:
datetime.datetime.strptime(i,"%d/%m/%Y %I:%M:%S %p")
except:
try:
datetime.datetime.strptime(i,"%d/%m/%y %I:%M:%S %p")
# and so on....

Related

Correct reading of datetime with AM/PM format

I'm trying to read some csv files that contain a column called 'timestamp' with this format:
7/6/2022 7:30:00 PM which should translate to (mm/dd/YYYY hh:mm:ss). What I tried was after reading the csv file using:
df['timestamp']= pd.to_datetime(df['timestamp'],format='%m/%d/%Y %I:%M:%S %p')
And it renders a totally different thing with this error:
ValueError: time data '07-06 19:30' does not match format '%m/%d/%Y %I:%M:%S %p' (match)
'07-06 19:30' This value is the same that appears when reading the csv directly with no formatting which is strange as when I open the csv the full date is there. I'm a bit lost on this case as it appears as I cannot convert the date.
Thanks
The format='%m/%d/%Y %I:%M:%S %p' should work, make sure you read your data as string.
That said, pandas is advanced enough to figure out the format semi-automatically, the only ambiguity to resolve is to specify that the first digits are not days:
df['new_timestamp'] = pd.to_datetime(df['timestamp'], dayfirst=False)
example:
timestamp new_timestamp
0 7/6/2022 7:30:00 PM 2022-07-06 19:30:00

What is the proper format for code for this datetime.strptime function?

I have a python program that ingests and processes data, yet one field is not converting properly. One piece of data comes in as a string of java.time.OffsetDateTime.now(ZoneOffset.UTC) and we use strptime to create a datetime object. Here is the simplified code:
$ python
from datetime import datetime
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
# this works yet is not in the source format
date_string = "2021-06-28T19:47:27.510670"
datetime_object = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f')
print (datetime_object)
Results in this error
ValueError: unconverted data remains: 082Z
What is the proper format code to create the datetime object?
Just use dateutil. You have time in ISO 8601 format with setting of timezone
from dateutil import parser
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
datetime_object = parser.parse(date_string)
print(datetime_object) # 2021-06-28 19:47:27.510670+00:00

How to convert all possible types of datetime formats using python module

Is it possible to convert all possible types of datetime formats to '%Y-%m-%d %H:%M:%S' without error.
For example, '2016-01-21 12:36:59.124' or '2016-Jan-12 21:36:12' or '16-January-23 23:59:32.1should be converted to %Y-%m-%d %H:%M:%S format without raising any error?
from dateutil import parser
print parser.parse('2016-01-21 12:36:59.124')
print parser.parse('2016-Jan-12 21:36:12')
print parser.parse('16-January-23 23:59:32.1')
Output:
2016-01-21 12:36:59.124000
2016-01-12 21:36:12
2023-01-16 23:59:32.100000
using strftime() and strptime() functions you would be able to convert them without issues.

how to convert and subtract dates, times in python

I have the following date/time:
2011-09-27 13:42:16
I need to convert it to:
9/27/2011 13:42:16
I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parses the date fine but sadly it doesn't seem to get the time correctly. I also tried to use another method I found on stackoverflow that uses "time", but I get an error that time is not defined.
You can use datetime's strptime function:
from datetime import datetime
date = '2011-09-27 13:42:16'
result = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
You were lucky, as I had that above line written for a project of mine.
To print it back out, try strftime:
print result.strftime('%m/%d/%Y %H:%M:%S')
Use python-dateutil:
import dateutil.parser as dateparser
mydate = dateparser.parse("2011-09-27 13:42:16",fuzzy=True)
print(mydate.strftime('%m/%d/%Y T%H:%M:%S'))
http://docs.python.org/library/datetime.html#datetime.datetime.strptime
and
http://docs.python.org/library/datetime.html#datetime.datetime.strftime
(And the rest of the datetime module.)

Grabbing & displaying the current time

I'm very new to python and trying to build a simple web app in pieces.
I'm using the datetime library for the first time so please be patient with me.
All I'm trying to do is to get and display the current time and date so that I can cross-reference it with a target time & date later.
I'm getting some colossal errors. Any help is appreciated. Not sure what I'm doing incorrectly here to display the time formatted the way I want.
from datetime import datetime
date_string = "4:21 PM 1.24.2011"
format = "%I.%M %p %m %d, %Y"
my_date = datetime.strptime(date_string, format)
print(my_date.strftime(format))
The format of the date_string doesn't match the format you're trying to parse it with. The following format string should allow you to parse the date.
format = "%I:%M %p %m.%d.%Y"
And afterwards, if you want to print it using the other format
print(my_date.strftime("%I.%M %p %m %d, %Y"))
You're using wrong format string. Try to replace it with "%I:%M %p %m.%d.%Y".
Here's documentation how to use datetime class properly.
The problem is with your format. You need to make the format match date_string. So try this:
format = "%I:%M %p %m.%d.%Y"
That should do the trick
Also, it might be of interest to you to take a look at time.asctime

Categories