Getting datetime object to print as a real date

Related searches

I have a text file with rows like this..

(datetime.datetime(2017, 1, 1, 4, 16), 0.17799999999999999)
(datetime.datetime(2017, 1, 1, 4, 26), 0.20000000000000001)
(datetime.datetime(2017, 1, 1, 4, 36), 0.17699999999999999)

Ultimately I want to read in the data and plot the date against the value, but I'm currently stuck on just getting the data read.

So far I have

f=open('data.txt', 'r')
for line in f:
    line = line.strip()
    columns = line.rsplit(',',1)                                                                                                                             

Sample output:

datetime.datetime(2017, 1, 1, 4, 36)

But I would like it to print as a date e.g. 20170101 04:36:00 (or similar) I don't know how to get the datetime object to to get recognized as such, and display as a real date string. If I google it I see loads of info on turning a string to a datetime object but nothing for the other way round.

Many thanks in advance.

You can use regex to extract the integers from the datetime part of the string and use these to create a datetime object. You can then manipulate the datetime object as you please to print the desired output:

import re
from datetime import datetime

regex_match = re.match(r'.*?(\d+), (\d+), (\d+), (\d+), (\d+).*', 'datetime.datetime(2017, 1, 1, 4, 36)').groups()
d = datetime(*[int(i) for i in regex_match])

And you can then choose how to print this:

>> d = datetime(2017, 1, 1, 4, 16)
>> print(d.isoformat())
.. 2017-01-01T04:16:00

Or with more control over printing:

>> d.strftime("%Y%m%d %H:%M:%S")
.. '20170101 04:16:00'

So in your code it is:

f=open('data.txt', 'r')
for line in f:
    line = line.strip()
    columns = line.rsplit(',',1)                                                                                                                             
    regex_match = re.match(r'.*?(\d+), (\d+), (\d+), (\d+), (\d+).*', date).groups()
    d = datetime(*[int(i) for i in regex_match])
    print(d.strftime("%Y%m%d %H:%M:%S"))

Once you have the datetime object, you can also use matplotlib (you referenced wanting to plot this) to convert a datetime object to a readable string (ref: Plotting dates on the x-axis with Python's matplotlib):

import matplotlib.pyplot as plt
your_datetime_array = [(datetime.datetime(2017, 1, 1, 4, 16), 0.17799999999999999),
(datetime.datetime(2017, 1, 1, 4, 26), 0.20000000000000001),
(datetime.datetime(2017, 1, 1, 4, 36), 0.17699999999999999)]

x = [tup[0] for tup in your_datetime_array]
y = [tup[1] for tup in your_datetime_array]

plt.xticks(rotation=-45) # rotate them if you want
ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))

plt.plot(x, y)

Note that changing the '%Y-%m-%d %H:%M' string will change the format that is plotted.

Python Datetime Tutorial: Manipulate Times, Dates, and Time Spans, It can extract the day of the week, day of the month, and other date and in our interactive course, where you can write real code and get instant feedback. We' ll print our datetime object, and then also print its type using� Angular Date Pipe Examples. Now we will go through few angular date pipe examples to understand it further. I have created a date pipe component in my Angular project and added current datetime values in different formats like milliseconds,date object,datetime string,ISO datetime string.

The contents of the text file in your example is valid Python syntax, so if you are sure this format is correct, and the data is under your own control, you could just evaluate the lines. (Note that this is a security risk if the data can be manipulated by others, so this may or may not be a good solution depending on your use case.)

import datetime

with open('data.txt', 'r') as file:  # Tip: use context manager to avoid resource leak
    for line in file:
        line = line.strip()
        date = eval(line)[0]  # evaluate line as Python code and get first element
        print(date.strftime('%Y%m%d %H%M'))  # print date/time in preferred format

Using Python datetime to Work With Dates and Times – Real Python, Python's standard library includes a module called time that can print the You can try the code below to get a sense of how each object is� Get the current date & time using () Python provides a module datetime which has a class datetime. It provides a method now (). (tz=None) (tz=None) It returns a datetime class object containing the current date & time information in provided timezone.

An alternative to eval or regex could be parse module:

import parse
import datetime as dt

f = open('mytext.txt', 'r')
template = "(datetime.datetime({Y}, {m}, {d}, {H}, {M}), {v})"
for line in f:
    x = parse.parse(template, line).named
    Y, m, d, H, M = int(x["Y"]), int(x["m"]), int(x["d"]), int(x["H"]), int(x["M"])
    ts = dt.datetime(Y, m, d, H, M)
    print(ts.strftime("%Y%m%d %H:%M:00"))


20170101 04:16:00
20170101 04:26:00
20170101 04:36:00

How to get current date and time in Python?, We will also format the date and time in different formats using strftime() method. from datetime import date today = print("Today's date:", today). A DateTime object is in the local time zone unless explicitly created in the UTC time zone. var dDay = new DateTime.utc(1944, 6, 6); Use isUtc to determine whether a DateTime object is based in UTC. Use the methods toLocal and toUtc to get the equivalent date/time value specified in the other time zone. Use timeZoneName to get an abbreviated name of the time zone for the

You can try this :

import datetime
import dateutil.parser 
date = '2014-12-18T19:00:00-07:00'
 print (date.strftime("%Y-%m-%d %H:%M:%S"))

How to Get the Current Date and Time in Python, We can use the now() function to get the an object with the current date and time: current_datetime = print(current_datetime). The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several.NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

How to Format Dates in Python, However, Python date objects make it extremely easy to convert In another scenario, you may want to extract the month in string format from a numerically formated date value. import datetime today = print(today) string as a datetime until we convert it to an actual datetime object. Public ReadOnly Property Date As DateTime Property Value DateTime. A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00). Examples. The following example uses the Date property to extract the date component of a DateTime value with its time component set to zero (or 0:00:00, or midnight). It

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types

  • So your file actually has raw datetetime objects saved as a string like (datetime.datetime(2017, 1, 1, 4, 16), 0.17799999999999999)
  • Yes that's right. It gets pulled from a database that way. (Im struggling to format these comments!)
  • Why are you pulling from the database and saving it to a txt file? Instead of pulling these directly and processing them?
  • We have to keep database interaction to a minimum, so I was just going to pull all the data in one dump then not have to touch the db again.
  • How are you pulling from data and pushing to txt, you know you can save the datetime object as a string right?
  • Thanks, I gave that a try. Now I get the error AttributeError: 'str' object has no attribute 'strftime'
  • And you definitely have the line: d = datetime.datetime(*[int(i) for i in regex_match]) before d.strftime("%Y%m%d %H:%M:%S")? Note the "d" and not "date" as in your original code. "date" was a string object but "d" is of type datetime.
  • I hadn;t the first time but now I have got that all as you suggest. The error is a bit different now. It says AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
  • Have you got: import datetime at the top of your file? Also make sure you are not calling any other variable datetime
  • I just tried it as you suggested and did 'import datetime' only. And it works! Thank you so much!
  • I was writing the exactly same answer and wondering why the others were not simply eval() the string. :-)
  • I'm not sure how this applies to strings that are already in datetime object format. Though not apparently real datetime objects.