Issue with datetime string format - python

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)

Related

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

How to convert string contains datetime in isoformat to date and time values?

I have the following string format (Python 3.6):
'2018-11-19T10:04:57.426872'
I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'
I tried to convert it with:
from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')
But this gives:
ValueError: unconverted data remains: T10:04:57.426872
In the above example I want to see:
start_date = '2018-11-19'
start_time = '10:04'
Since the date seems to be in ISO-Format, a simple
start = datetime.datetime.fromisoformat(text)
will parse it correctly. From there you can get your date and time with
start_date = start.strftime("%Y-%m-%d")
start_time = start.strftime("%H:%M")
Edit:
For Python < 3.7, you can use this format:
start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")
For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.
Try this:We have one of the best package for parsing dates called dateutil.
from dateutil import parser
date1='2018-11-19T10:04:57.426872'
print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
print 'Start_time:',parser.parse(date1).strftime("%H:%M")
Result:Start_date:2018-11-19
Start_time:10:04
You need to parse the entire string into one datetime object and then extract your required values from that.
dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
d = dt.date()
t = dt.time()
print(d.strftime('%Y-%m-%d'))
print(t.strftime('%H:%M'))
Which outputs:
2018-11-19
10: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')

convert a string to datetime format

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())

How to convert strftime or string format to timestamp/Date in python?

I am very new to Python coding. I was trying to get the start and end date of a month and then compare it with another date column in the same excel.
I only need the date in mm/dd/yy format but do not need the time.
The final_month_end_date is basically a string format which I compare with an actual date but it gives me an error saying
"TypeError: Cannot compare type 'Timestamp' with type 'str'"
I have also tried .timestamp() function but of no use.
How can I resolve this problem?
import datetime as dt
import strftime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= calendar.monthrange(current_year,current_month)[1]
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
To convert a string to a DateTime object use datetime.strptime. Once you have the datetime object, convert it to a unix timestamp using time.mktime.
import time
import datetime as dt
from time import mktime
from datetime import datetime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= "30"
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
# Use datetime.strptime to convert from string to datetime
month_start = datetime.strptime(month_start_date, "%Y/%m/%d")
month_end = datetime.strptime(final_month_end_date, "%Y/%m/%d")
# Use time.mktime to convert datetime to timestamp
timestamp_start = time.mktime(month_start.timetuple())
timestamp_end = time.mktime(month_end.timetuple())
# Let's print the time stamps
print "Start timestamp: {0}".format(timestamp_start)
print "End timestamp: {0}".format(timestamp_end)

Categories