Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Datetime format with underscore

I've declared date as a string like this,

from_date = '2018_04_01'

and converted it into datetime format,

from_date = datetime.datetime.strptime(str(from_date), "%Y_%m_%d")

the from date now is formatted as,

2018-04-01

I want the from date with underscore, and in datetime format.

strftime would return the required format but in string. This could be again formatted to a datetime format - this is the worst possible and cumbersome way to do it.

like image 570
Zedaiq Avatar asked Apr 25 '18 06:04

Zedaiq


People also ask

What is strftime and Strptime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

Why do we use Strptime?

Python Strptime Format Strptime python is used to convert string to datetime object. Note - format "%d/%m/%y" represents the the corresponding "9/23/20" format. The output of the above command will be a Python datetime object.


1 Answers

You mean something like this ?

from datetime import datetime, date

print "{:%Y_%m_%d}".format(datetime.now())
like image 54
d-coder Avatar answered Oct 23 '22 05:10

d-coder