How to change a datetime format in python? - 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

Related

How to change to datetime format date with dashes?

I have a date in format 2022-12-16T16-48-47" and I would like to change it to datetime using function pd.to_datetime.
My first idea was to create split the string to have it in more readable way:
string = "2022-12-16T16-48-47"
date, hour = string.split("T")
string = date + " " + hour
string
And now to use:
import pandas as pd
pd.to_datetime(string, format = "%Y-%M-%D %h-%m-%S")
But I have error:
ValueError: 'D' is a bad directive in format '%Y-%M-%D %h-%m-%S'
Do you know how it should be done properly?
Use Y, m, d and H, M, S instead:
>>> pd.to_datetime(string, format = "%Y-%m-%d %H-%M-%S")
Timestamp('2022-12-16 16:48:47')
>>>
You should check out the strftime format codes documentation for better understanding.

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)

Get current date from datetime.datetime

I'm trying to get current date so I can pass it to the DATE field in SQL. I'm using datetime.datetime, below is my code:
from datetime import datetime
dt = datetime.strptime(datetime.today().date(), "%m/%d/%Y").date()
However, i'm getting this error:
TypeError: strptime() argument 1 must be str, not datetime.datetime
How can I fix the issue above? I'm still confused about datetime and datetime.datetime, and i want to keep using from datetime import datetime not import datetime.
How can I fix the issue above? thank you
If you see closely, the result of following statement,
>>> datetime.today().date()
datetime.date(2019, 9, 30)
>>> str(datetime.today().date())
'2019-09-30'
You'll notice that the datetime returned is - seperated and you'll have to convert it explicitly to a string value. Hence, for the above statement to work, change it to :
dt = datetime.strptime(str(datetime.today().date()), "%Y-%M-%d").date()
Then change it to whatever format you desire for using strftime (in your case >>> "%d/%m/%Y")
>>> dt.strftime("%d/%m/%Y")
'30/01/2019'
Just use datetime.strftime:
from datetime import datetime
dt = datetime.today().strftime("%m/%d/%Y")
print(dt)
Prints:
'09/30/2019'
strptime takes a string and makes a datetime object. Whereas strftime does exactly the opposite, taking a datetime object and returning a string.

The time data does not match format

Hello I am trying to convert a string which is a = "2019-04-22 00:00" to a datetime but it does not work, I tried this :
a = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M')
But I got
time data 'start_period' does not match format '%Y-%m-%d %H:%M'
I precise start_period is get by this : a = request.POST.get('start_period')
Like this it should work:
import datetime
start_period = "2019-04-22 00:00"
a = datetime.datetime.strptime(start_period, '%Y-%m-%d %H:%M')
Result:
datetime.datetime(2019, 4, 22, 0, 0)
May I suggest using dateutil module, where you do not need to provide the format string
from dateutil import parser
print(parser.parse("2019-04-22 00:00"))
#2019-04-22 00:00:00
there are multiple ways to convert string to datetime in python. it is based on the requirement of the user which function to use.
one possible solution could be as given below.
import timestring
start_period = "2019-04-22 00:00"
print(timestring.Date(start_period))

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