For a course I am taking, we have a tab delimited flat file that I am importing into Python 3 using a Jupyter Notebook. The format of the date time is below and again it is currently a text string.
Sat Jul 25 04:43:04 0000 2020
How do I change this from text to a date/time in Python 3?
How do I change the date/time format to be: YYYY-MM-DD HH:MM?
Thanks,
CodePudding user response:
Use the datetime standard module:
- https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
- https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime
Example:
import datetime
s = 'Sat Jul 25 04:43:04 0000 2020'
dt = datetime.datetime.strptime(s, '%a %b %d %H:%M:%S %z %Y')
string = dt.strftime('%Y-%m-%d %H:%M') # -> 2020-07-25 04:43
CodePudding user response:
from datetime import *
test = 'Sat Jul 25 04:43:04 0000 2020'
year = test[-4:]
month = test[4:7]
day = test[8:10]
time = test[12:19]
adjusted_date = f'{day}-{month}-{year}-{time}'
x = datetime.strptime(adjusted_date, "%d-%b-%Y-%H:%M:%S")
z = datetime.strftime(x, "%d-%m-%Y-%H:%M")
print(z)
OUTPUT:
2020-07-25 04:43
The easiest way I could think about right now. Hope that helps and answers your question.
Before anyone complains. User asking question is definitely new to programming. Reading docs etc it is like a black magic when you just started, all this %Y%M%D means nothing :D so above it is (imo) the most easy to understand way of doing it, self-explanatory.. and if someone is struggling with slicing.. then it should go back and learn it.