The war in Europe had ended in early May 1945 (on the 7, 8, or 9 depending on time zones and affiliations with the Commonwealth, French, or Soviets, respectively). However, the first atomic detonation did not occur until the test at Los Alamos on 16 July 1945
But why were the atomic bombs actually used on Japan? Back on 19 August 1943, the US and the UK had signed the Quebec Agreement, which states "that we will not use it against third parties without each other's consent." Before the attack on Hiroshima, the US sought UK consent. Why would the UK consent? And why would the US want that consent?
Or, to combine the two questions, why would the UK and the US agree that using an atomic weapon against Japan is a good idea?
From a moral standpoint, we must remember that this would be the first atomic attack in war, so it would have been hard to determine how terrifying an atomic bomb would be compared to firebombing. In addition, many firebombing attacks had already thoroughly destroyed cities that were much larger and more significant than Hiroshima and Nagasaki. The casualties in Tokyo during Operation Meetinghouse were also arguably higher than that of Hiroshima or Nagasaki, depending on the figures given by various sources. Along that line of thought, would dropping many bombs to destroy military targets and incur civilian casualties be any worse than dropping one bomb to destroy military targets and incur civilian casualties?
From a military and political perspective, invading Japan was not very attractive because of the massive casualty projections. In addition, the Soviets had promised twice before (the Tehran Conference of November 1943 and the Yalta Conference of February 1945) to enter the Pacific Theater within 3 months of the end of the European war. This deadline was coming up before the US would be ready to launch Operation Downfall, the invasion of Japan itself, which was scheduled for October 1945. Anymore delays would only result in greater Soviet influence in Asia. Wiping out the entire Japanese nation probably was not an attractive idea either, so using atomic bombs to destroy "only" a few cities before the Soviets landed on Honshu was more appealing
The greatest tragedy in the selections of Hiroshima and Nagasaki is that they were not always the intended primary target. The original list of targets also included Kokura, Yokohama, Niigata, and Kyoto. However, Kyoto was later removed from the list by "Henry L. Stimson, the Secretary of War at the time, who had known and admired Kyoto ever since his honeymoon there several decades earlier." Nagasaki replaced Kyoto on the list
Sources:
Russia had pushed into Germany and by April 1945 Germany had surrendered. The atomic bomb was still being developed during the summer of 1945.