-1

Is there any simple way to create a pattern in datetime? If I have a timestamp that looks like this

2019-04-28 21:22:00

I could create a pattern in Java that looks like this

yyyy-MM-dd HH:mm:ss

Is there something similar in Python?

SuperKogito
  • 2,998
  • 3
  • 16
  • 37
  • check https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior –  Apr 28 '19 at 19:24
  • [Yes](https://docs.python.org/3.7/library/datetime.html?highlight=datetime.strftime#datetime.datetime.strftime). – ForceBru Apr 28 '19 at 19:24
  • 1
    Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – wjandrea Apr 28 '19 at 19:34
  • 2
    From the current wording of the question, it's a bit hard to tell exactly what you're after here. Are you starting with a string and you want to end up with a datetime object or the other way around or something else? – Henry Woody Apr 28 '19 at 19:44

1 Answers1

1

You can do this using the strftime method of the datetime object from the datetime library.

In your case you would use the following format string:

"%Y-%m-%d %H:%M:%S"

Example usage:

import datetime as dt

my_time = dt.datetime.now()
my_formatted_time = my_time.strftime("%Y-%m-%d %H:%M:%S")

print(my_formatted_time)

with result:

2019-04-28 12:30:46
Henry Woody
  • 14,024
  • 7
  • 39
  • 56