convert a string to datetime format - python

How should I fix this?
error is:
ValueError: time data '2016-10-20 03:43:11+00:00' does not match format '%Y-%m-%d %H:%M:%S%z'
code is:
fmt = "%Y-%m-%d %H:%M:%S%z"
dt = datetime.strptime(row['Time'], fmt)

a bit of search would give you some nice solutions.
first option:
from datetime import datetime as dt
t = '2016-10-20 03:43:11+00:00'
fmt = "%Y-%m-%d %H:%M:%S+00:00"
d = dt.strptime(t, fmt)
# output datetime.datetime(2016,10,20,3,43,11)
second option:
from dateutil import parser as psr
t = '2016-10-20 03:43:11+00:00'
d = psr.parse(t)
# output datetime.datetime(2016,10,20,3,43,11, tzinfo=tzutc())

Related

How to convert string 2021-09-30_1 to datetime

How can I convert string 2021-09-30_1 to datetime 2021/09/30 00:00, which means that from the last string we have to substract one to get the hour.
I tried datetime.strptime(date, '%Y %d %Y %I')
datetime.strptime if to define the timestamp from a string, the format should match the provided one. datetime.strftime (note the f) is to generate a string from a datetime object.
You can use:
datetime.strptime(date, '%Y-%m-%d_%H').strftime('%Y/%m/%d %H:%M')
output: '2021/09/30 01:00'
in case the _x defines a delta:
from datetime import datetime, timedelta
d, h = date.split('_')
d = datetime.strptime(d, '%Y-%m-%d')
h = timedelta(hours=int(h))
(d-h).strftime('%Y/%m/%d %H:%M')
output: '2021/09/29 23:00'
Considering the _1 is hour and appears in al of your data (The hour part takes value between [1, 24]), your format was wrong.
For reading the date from string you'll need format it correctly:
from datetime import datetime, timedelta
date = "2021-09-30_1"
date_part, hour_part = date.split("_")
date_object = datetime.strptime(date_part, '%Y-%m-%d') + timedelta(hours=int(hour_part) - 1)
Now you have the date object. And you can display it as:
print(date_object.strftime('%Y/%m/%d %H:%M'))
from datetime import datetime
raw_date = "2021-09-30_1"
date = raw_date.split("_")[0]
parsed_date = datetime.strptime(date, '%Y-%m-%d')
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')
strptime is used for parsing string and strftime for formating.
Also for date representation you should provide format codes for hours and minutes as in:
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')

Issue with datetime string format

Im trying to convert a datetime object to a string but it does not seem to give me the desired output.
from datetime import datetime
cur_time = datetime.now()
last_runtime = cur_time.strftime("%Y-%m-%dT%H:%M:%S.%f+%Z")
print(last_runtime)
My current output:
2021-10-13T09:09:27.824592+
My desired output:
2021-10-13T09:09:27.825+00:00
You can use .astimezone() and small z on the format string:
from datetime import datetime
cur_time = datetime.now()
last_runtime = cur_time.astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
last_runtime = "{0}:{1}".format(
last_runtime[:-2],
last_runtime[-2:]
)
print(last_runtime)

How to parse date time string with offset?

I am trying to parse this string:
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S %Z')
But, it doesn't work. However, I am not sure how to properly put this into a datetime object. How would I do this?
Your:
string_date = "2020-10-06T12:31:15-05:00"
seems like ISO format for me, so I did:
import datetime
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.fromisoformat(string_date)
print(dt)
print(dt.tzinfo)
Output:
2020-10-06 12:31:15-05:00
UTC-05:00
Is above what are you looking for?

How to change a datetime format in python?

How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04

Python: Get date format as a string from datetime64[ns]

I want to determine the date format of an input datetime64[ns] value, and obtain a str.
Example:
input value = 1978-07-06
output value = '%Y-%m-%d'
I've tried this but got stuck:
import dateutil.parser
from datetime import datetime
yourdate = dateutil.parser.parse(input)
datetimeobject = datetime.strptime(yourdate,'%Y-%m-%d %H:%M:%S')
Any help on this would be appreciated.
Note: dateinfer gave me "No module named 'infer' " error
extract the date, from input using regular expression
import dateutil.parser
from datetime import datetime
input = '1978-07-06' # or - 06/07/1978
date_obj = dateutil.parser.parse(input)
date_string = date_obj.strftime('%Y-%m-%d %H:%M:%S')

Categories